我正在使用实体框架。 我有这种情况:
Obj1: ( ID (Primary key ) , name )
Obj2: ( ID ( Primary key ) , FromID ( foreign key obj1) , ToID (foreign key obj1) , quantity )
所以obj1和obj2之间有2个关系。 我想从obj1中选择所有obj2和所有相关的东西。 我应该如何包括:
1. context.obj2.Include("FromID").Tolist
or
2.context.obj2.include ("FromID").Include("ToID").Tolist
因为集合FromID和ToID可能包含全部或部分相同的项目。
谢谢!
答案 0 :(得分:1)
因此,在您的实体框架POCO中,您所描述的模型类看起来像这样:
public class Obj1
{
public int ID { get; set;}
public string name { get; set; }
}
public class Obj2
{
public int ID { get; set; }
public int FromID { get; set; }
public int ToID { get; set; }
public int quantity { get; set; }
}
您描述的密钥会使用Data Annotations
表示以下添加内容public class Obj1
{
[Key]
public int ID { get; set;}
public string name { get; set; }
}
public class Obj2
{
[Key]
public int ID { get; set; }
public int FromID { get; set; }
public int ToID { get; set; }
public int quantity { get; set; }
}
您没有在模型中明确提及任何导航属性,但您希望使用Include
这一事实意味着您需要一些......我将为每个外键关系添加一些列出,在关系的两侧都有导航属性 - 请参阅InverseProperty and ForeignKey (attributes):
public class Obj1
{
public Obj1
{
Froms = new List<Obj2>();
Tos = new List<Obj2>();
}
[Key]
public int ID { get; set;}
public string name { get; set; }
[InverseProperty("From")]
public virtual ICollection<Obj2> Froms { get; set; }
[InverseProperty("To")]
public virtual ICollection<Obj2> Tos { get; set; }
}
public class Obj2
{
[Key]
public int ID { get; set; }
public int quantity { get; set; }
public int FromID { get; set; }
[ForeignKey("FromID")]
public virtual Obj1 From { get; set; }
public int ToID { get; set; }
[ForeignKey("ToID")]
public virtual Obj1 To { get; set; }
}
所以,现在我们已经设置了所有模型类,我们可以看到你的关系 - 一对多 - 实际上只有在走另一条路时才需要Include
:
var obj1sWithAllFromsAndTos = context.Obj1s
.Include(o => o.Froms)
.Include(o => o.Tos)
.ToList();
而不是
var obj2s = context.Obj2.ToList();
已在其Obj1
和From
属性中包含每个相关的To
。