繁体   English   中英

如何在实体框架核心中填写自引用表

[英]how to fill Self Reference Table in entity framework core

我在我的 .net 核心 3.1 应用程序中使用实体框架核心。 我有一个 object 之类的

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; }
 }

如何让我的 object 在 model 创建时加载父 object。 model 创建的当前代码是

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用于建立表之间的关系。

在加载带有父 object 的 object 之前,您需要更改OnModelCreating中的代码。 WithOne需要指定一个 object。

    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以引用子 object。

 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; } public AppEntity Parent { get; set; } public AppEntity Parent { get; set; } ,并删除builder.Entity<AppEntity>().HasOne(j => j.Parent).WithOne().HasForeignKey<AppEntity>(f => f.parent_id); .

往表中插入数据前,查询entity_id是否存在,如果存在则添加,不存在则设置null。 因为主键有自己的索引,所以查询速度很快。

查询时,基于这两列,可以使用子查询或关联查询,对对应的数据进行清晰的处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM