对于一对多关系,已有很多和拥有很多有什么区别?我什么时候应该使用另一个?
例如:
public class xxx
{
public virtual IReadOnlyCollection<xxxHistoryEntity> Histories => _histories;
private readonly List<xxxHistoryEntity> _histories = new List<xxxHistoryEntity>();
}
public class xxxHistoryEntity : Entity<string>
{
public string State { get; set; }
public string NodeId { get; set; }
public string Message { get; set; }
}
实体配置:
class xxxConfiguration
: IEntityTypeConfiguration<xxx>
{
public void Configure(EntityTypeBuilder<xxx> builder)
{
builder.OwnsMany(itm => itm.Histories, collbuilder =>
{
collbuilder.HasForeignKey("xxxid");
});
}
}
class xxxHistoryConfiguration
: IEntityTypeConfiguration<xxxHistoryEntity>
{
public void Configure(EntityTypeBuilder<xxxHistoryEntity> builder)
{
builder.ToTable("xxx_histories");
builder.HasKey(itm => itm.Id);
builder.Property(itm => itm.Id)
.ValueGeneratedOnAdd();
}
}
生成的迁移如下:
migrationBuilder.CreateTable(
name: "xxx_histories",
columns: table => new
{
id = table.Column<string>(nullable: false),
xxxid = table.Column<string>(nullable: false),
state = table.Column<string>(nullable: true),
nodeid = table.Column<string>(nullable: true),
message = table.Column<string>(nullable: true),
xmin = table.Column<uint>(type: "xid", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_xxx_histories", x => new { x.id, x.xxxid });
table.ForeignKey(
name: "fk_xxxhistoryentity_xxx_xxxarid",
column: x => x.xxxid,
principalTable: "xxx",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
如果我通过用HasMany替换OwnsMany来更新 xxxConfiguration ,例如:
class xxxConfiguration
: IEntityTypeConfiguration<xxx>
{
public void Configure(EntityTypeBuilder<xxx> builder)
{
builder.HasMany(itm => itm.Histories)
.WithOne()
.HasForeignKey("xxxid");
}
}
生成的迁移如下:
migrationBuilder.CreateTable(
name: "xxx_histories",
columns: table => new
{
id = table.Column<string>(nullable: false),
xxxid = table.Column<string>(nullable: false),
state = table.Column<string>(nullable: true),
nodeid = table.Column<string>(nullable: true),
message = table.Column<string>(nullable: true),
xmin = table.Column<uint>(type: "xid", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_xxx_histories", x => new { x.id, x.xxxid });
table.ForeignKey(
name: "fk_xxxhistoryentity_xxx_xxxid",
column: x => x.xxxid,
principalTable: "xxx",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
如您所见,两者产生的迁移是相同的。那么OwnsMany有什么意义呢?
答案 0 :(得分:0)
摘自文档:
EF Core允许您对只能出现在 其他实体类型的导航属性。这些被称为拥有 实体类型。包含拥有的实体类型的实体是其所有者。
拥有的实体实质上是所有者的一部分,并且不存在 没有它,它们在概念上类似于聚合。
https://docs.microsoft.com/en-us/ef/core/modeling/owned-entities