C# 实体框架4中的单向一对多关联?
EF 4是否支持单向一对多关联,如:C# 实体框架4中的单向一对多关联?,c#,entity-framework-4,associations,C#,Entity Framework 4,Associations,EF 4是否支持单向一对多关联,如: public class Parent { public int Id { get; set; } public string Something { get; set; } public List<Child> AllMyChildren { get; set; } } public class Child { public int Id { get; set; } public string Anotherthing {
public class Parent
{
public int Id { get; set; }
public string Something { get; set; }
public List<Child> AllMyChildren { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Anotherthing { get; set; }
// I don't want a back-reference to the Parent!
// public int ParentId { get; set; }
}
公共类父类
{
公共int Id{get;set;}
公共字符串Something{get;set;}
公共列表AllMyChildren{get;set;}
}
公营儿童
{
公共int Id{get;set;}
公共字符串另一个对象{get;set;}
//我不想要一个对家长的反向引用!
//public int ParentId{get;set;}
}
当我尝试使用父级和子级之间的关联编译项目时,其中End2导航为空(因为我在“添加关联”对话框中取消选中了End2导航属性复选框),我得到
错误2027:未为以下EntitySet/AssociationSet-Child指定映射
更新:
如果我只是在父对象上有一个列表或类似的属性,而不是列表呢?我是否需要创建一个包装类型来保存字符串,以便我还可以保留对父级的回引用?相信这可以使用Fluent API(定义单向关联的唯一方法)实现
modelBuilder.Entity()
.HasKey(t=>t.Id);
modelBuilder.Entity()
.HasMany(p=>p.AllMyChildren)
.WithRequiredPrincipal();
您为什么不想要反向引用?为什么这会困扰你?这是EF的默认行为,我不认为您可以关闭它-关联始终是双向的street@marc_s:子级永远不需要引用其父级,也永远不会从一个父级移动到另一个父级。从业务对象的角度来看,不需要引用或关心父对象。如果我向父级添加一个引用,那只是为了满足持久性机制的要求。事实上,在我必须将Child更改为类以满足EF之前,它是一个具有一些简单属性的结构。@Eric J:好的,从纯粹主义者的角度来看,我理解你对这一点的看法。但是,为什么要与之抗争呢?只是要实事求是,接受你的框架的工作方式,并按照它的思路工作——而不是反对它。你会为自己省去很多悲伤。@marc_s:我喜欢从一个纯粹主义者开始(不管怎样,当我持有坚定的信念时),然后在知情的情况下决定以实用主义的名义退出哪里是有意义的。如果EF“只是不做单向的1:n关系”,这可能是一个合理的妥协,但我不知道这是真的。如果“纯粹主义者”都“接受现状”,EF4仍然不支持POCO;-)@Eric J:是的,没错:-)我想我们需要纯粹主义者和实用主义者,一起塑造工具及其功能集:-)
modelBuilder.Entity<Child>()
.HasKey(t => t.Id);
modelBuilder.Entity<Parent>()
.HasMany(p => p.AllMyChildren)
.WithRequiredPrincipal();