使用代码优先的实体框架和.NET 4,我尝试在父母与孩子之间创建一对多关系:
public class Parent
{
[Key]
public int ParentId { get; set; }
[Required]
public string ParentName { get; set; }
public IEnumerable<Child> Children { get; set; }
}
public class Child
{
[Key]
public int ChildId { get; set; }
[ForeignKey]
public int ParentId { get; set; }
[Required]
public string ChildName { get; set; }
}
正如所指出的here https://stackoverflow.com/questions/8452725/entity-framework-map-foreign-key-without-navigation-property/8455916#8455916,为了将外键关系带入数据库,必须链接实际对象,而不仅仅是它们的 ID。如果子级包含对其父级的引用(example https://stackoverflow.com/a/5543702/1180926).
但是我如何强制执行外键my实现,这是相反的方式(父引用子)?
首先:你不能使用IEnumerable<T>
用于集合导航属性。 EF 将忽略此属性。使用ICollection<T>
反而。
当您更改此设置时,在您的特定示例中,您不需要执行任何操作,因为外键属性名称遵循约定(主键名称ParentId
主要实体Parent
)以便 EF 将检测之间所需的一对多关系Parent
and Child
自动地。
如果您有另一个“非常规”FK 属性名称,您仍然可以使用 Fluent API 定义这样的映射,例如:
public class Child
{
[Key]
public int ChildId { get; set; }
public int SomeOtherId { get; set; }
[Required]
public string ChildName { get; set; }
}
Mapping:
modelBuilder.Entity<Parent>()
.HasMany(p => p.Children)
.WithRequired()
.HasForeignKey(c => c.SomeOtherId);
据我所知,不可能用数据注释来定义这种关系。的使用[ForeignKey]
属性需要外键属性所在的依赖实体中的导航属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)