有两个实体,关系如下:
public class CatalogNodeEntity : FullAuditedEntity<Guid>, IMultiTenant {
public virtual string Name { get; protected set; } public virtual string DisplayName { get; protected set; } private List<CatalogLayerEntity> Layers = new List<CatalogLayerEntity>(); }
public class CatalogLayerEntity:FullAuditedEntity<Guid>, IMultiTenant { public virtual string Name { get; protected set; } public virtual Guid? CatalogNodeId { get; set; } public virtual CatalogNodeEntity CatalogNode { get; set; } }
配置one to many 的实体关系,可这样配置
builder.Entity<CatalogNodeEntity>(m => { m.ToTable(options.TablePrefix + "CatalogNode", options.Schema); m.ConfigureByConvention(); m.Property(o => o.Name).IsRequired().HasMaxLength(CatalogConsts.MaxNameLength); m.HasMany(u => u.Layers).WithOne(u=>u.CatalogNode).HasForeignKey(u=>u.CatalogNodeId).OnDelete(DeleteBehavior.Cascade); });
这里有个坑需要注意,如果在WithOne的函数中没有指定实体,又在HasForeignKey中指定了外键,这是进行Migration就会出现两个外键
m.HasMany(u => u.Layers).WithOne().HasForeignKey(u=>u.CatalogNodeId).OnDelete(DeleteBehavior.Cascade);