我在.net core 3.1应用程序中使用实体框架核心。我有一个像
public class AppEntity
{
[Key]
public int entity_id { get; set; }
[Required]
public string entityname { get; set; }
[Required]
public string short_code { get; set; }
[Required]
public int entitytype_id { get; set; }
public int? parent_id { get; set; }
public AppEntity Parent { get; set; }
}
我如何在模型创建时使我的对象与父对象一起加载。模型创建时的当前代码是
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<AppEntity>(o => { o.HasIndex(e => e.short_code).IsUnique(true); });
builder.Entity<AppEntity>().HasOne(j => j.Parent).WithOne().HasForeignKey<AppEntity>(f => f.parent_id);
}
我在创建模型时出现异常
无法将属性或导航“父”添加到实体类型“ AppEntity”,因为在实体类型“ AppEntity”上已经存在具有相同名称的属性或导航。
就像评论所说,OnModelCreating
用来建立表之间的关系。
在使用父对象加载对象之前,您需要更改中的代码OnModelCreating
。在WithOne
需要特定的对象。
public DbSet<Entity> entities { get; set; }
public DbSet<AppEntity> appEntities { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<AppEntity>(o => {
o.HasIndex(e => e.short_code)
.IsUnique(true);
});
builder.Entity<AppEntity>()
.HasOne(j => j.Parent)
.WithOne(i=>i.appEntity)
.HasForeignKey<AppEntity>(f => f.parent_id);
}
因为您已经在dbcontext中创建了外键,所以可以删除[ForeignKey("parent_id")]
。
另外,在model中Entity
,您应该添加属性AppEntity
以引用子对象。
public class Entity
{
public int id { get; set; }
public AppEntity appEntity { get; set; }
}
然后,您可以Include
用来包含两个对象。
public virtual Entity GetById(int id)
{
var entity = _context.entities
.Include(y => y.appEntity)
.FirstOrDefault(x => x.id == id);
return entity;
}
编辑:
在一个表中,这将导致循环引用,因为您已添加parent_id
引用父对象。
更好的解决方案是删除public AppEntity Parent { get; set; }
,然后删除builder.Entity<AppEntity>().HasOne(j => j.Parent).WithOne().HasForeignKey<AppEntity>(f => f.parent_id);
。
在将数据插入表中之前,请查询entity_id是否存在,如果存在,则添加它,如果不存在,则将其设置为null。因为主键具有自己的索引,所以查询速度非常快。
在查询时,基于这两列,可以使用子查询或关联查询清楚地处理相应的数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句