使用部分键的实体框架代码优先自定义映射
是否可以使用 Entity Framework Code First 进行以下映射?
public class Parent
{
[Key]
public int ID {get; set;}
public string statecode{get; set;}
public virtual ICollection<Child> children{get; set;}
}
public class Child
{
[Key, Column(Order = 0)]
public string StateFromCode { get; set; }
[Key, Column(Order = 1)]
public string StateToCode { get; set; }
}
我想在 dbcontext 中指定一个关系,其中子级延迟加载到 Parent 中,并且 Parent.statecode == Child.StateToCode。请注意,StateToCode 是子键的一部分,而不是整个主键。如果可能的话,我应该在下面的数据库上下文中指定什么才能实现这一点?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Parent>().HasMany(x=>x.children)..............
}
Is it possible to do the following mapping with the Entity Framework Code First?
public class Parent
{
[Key]
public int ID {get; set;}
public string statecode{get; set;}
public virtual ICollection<Child> children{get; set;}
}
public class Child
{
[Key, Column(Order = 0)]
public string StateFromCode { get; set; }
[Key, Column(Order = 1)]
public string StateToCode { get; set; }
}
I would like to specify a relation in my dbcontext where children are lazy loaded into the Parent and Parent.statecode == Child.StateToCode. Note that StateToCode is part of the Child key and not the entire primary key. What should I specify in my DB context below to make this happen if possible at all?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Parent>().HasMany(x=>x.children)..............
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是不可能的 - 尤其是在代码优先的情况下,关系必须遵循与在数据库中指定引用约束完全相同的规则。因此,唯一有效的关系需要
Child
表中的Parent
的 Id 列以及该列上的外部约束It is not possible - especially not with code first where relations must follow exactly same rules as specifying referential constraint in the database. So the only valid relation will require
Parent
's Id column inChild
table and foreign constraint on this column