Entity Framework 一对多流利 Api - 外键
Entity Framework One to many fluent Api - foreign key
我想在两个实体之间建立联系。
我有 Entity_1 和 Entity_2 一对多关系(一个 Entity_1 可以有多个 Entity_2)。
所以我有我的实体:
实体
class Entity_1
{
public int Id { get; set; }
public int Entity_2Id{ get; set; }
public virtual Entity_2 Entity_2{ get; set; }
}
class Entity_2
{
public int Id { get; set; }
public int Entity_2Id{ get; set; }
public virtual ICollection<Entity_1> Entity_1s{ get; set; }
}
如何建立实体 2 中有外键 (Entity_1) 的连接?
one Entity_1 can have multiple Entity_2
这意味着,Entity_1
(可选)具有 Entity_2
的集合,并且 Entity_2
(可选)具有对 Entity_1
的引用:
class Entity_1
{
public int Id { get; set; }
public virtual ICollection<Entity_2> Entity_2s{ get; set; }
}
class Entity_2
{
public int Id { get; set; }
public int Entity_1Id { get; set; }
public virtual Entity_1 Entity_1 { get; set; }
}
而您的实体不正确。
上面代码的流利 API 是:
HasRequired(_ => _.Entity_1)
.WithMany(_ => _.Entity_2s)
.HasForeignKey(_ => _.Entity_1Id);
更多选项可用 here。
我想在两个实体之间建立联系。
我有 Entity_1 和 Entity_2 一对多关系(一个 Entity_1 可以有多个 Entity_2)。
所以我有我的实体: 实体
class Entity_1
{
public int Id { get; set; }
public int Entity_2Id{ get; set; }
public virtual Entity_2 Entity_2{ get; set; }
}
class Entity_2
{
public int Id { get; set; }
public int Entity_2Id{ get; set; }
public virtual ICollection<Entity_1> Entity_1s{ get; set; }
}
如何建立实体 2 中有外键 (Entity_1) 的连接?
one Entity_1 can have multiple Entity_2
这意味着,Entity_1
(可选)具有 Entity_2
的集合,并且 Entity_2
(可选)具有对 Entity_1
的引用:
class Entity_1
{
public int Id { get; set; }
public virtual ICollection<Entity_2> Entity_2s{ get; set; }
}
class Entity_2
{
public int Id { get; set; }
public int Entity_1Id { get; set; }
public virtual Entity_1 Entity_1 { get; set; }
}
而您的实体不正确。 上面代码的流利 API 是:
HasRequired(_ => _.Entity_1)
.WithMany(_ => _.Entity_2s)
.HasForeignKey(_ => _.Entity_1Id);
更多选项可用 here。