2015-02-12 175 views
0

我正在使用实体框架。 我有这种情况:实体框架:在双重相关对象上包含相关实体

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可能全部或部分相同的项目。

谢谢!

回答

1

所以,在你的实体框架波苏斯,你的模型类 - 你形容他们 - 会是这个样子:

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这一事实意味着您需要一些...我将为您列出的每个外键关系添加一些ñ在关系的双方avigation属性 - 见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; } 
} 

所以,现在我们都建立了模型类,我们可以看到,你们的关系 - 是1对多 - 实际上需要

var obj1sWithAllFromsAndTos = context.Obj1s 
            .Include(o => o.Froms) 
            .Include(o => o.Tos) 
            .ToList(); 

,而不是

var obj2s = context.Obj2.ToList(); 

这将已经包括各相关:走另一条路,只有当在其FromTo属性。

相关问题