因此,在您的实体框架 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();
这将在其From 和To 属性中包含每个相关的Obj1。