2013-12-16 66 views

回答

4

在EF中,通過使用導航屬性來完成連接表。基本上,EF爲你做。在存儲庫中實現時,可能是通用的或非通用的,在構建查詢表達式以告知EF爲您填充導航屬性時,您可以調用Include方法。

比方說,我們有這些POCO類:

public class Dog 
{ 
    public int DogId { get; set; } 
    public string Name { get; set; } 

    public int OwnerId { get; set;} 
    public Owner Owner { get; set; } // the navigation property 
} 

public class Owner 
{ 
    public int OwnerId { get; set; } 
    public string Name { get; set; } 

    // another navigation property 
    // all the dogs that are related or owned by this specific owner 
    public ICollection<Dog> DogList { get; set; } 
    public ICollection<Cat> CatList { get; set; } 
} 

下面是使用包括樣本代碼片段:

public virtual IEnumerable<Dog> Retrieve() 
{ 
    var _query = context.Dog.Include(a => a.Owner); 
    ... 
    ...// rest of your code 
} 

而對於多個表,你可以窩在包括方法,像這樣:

public virtual IEnumerable<Owner> Retrieve() 
{ 
    // you can nest as many as you want if there are more nav properties 
    var _query = context.Owner 
     .Include(a => a.DogList) 
     .Include(a => a.CatList); 
    ... 
    ...// rest of your code 
} 

一旦你包含導航屬性,那麼基本上就是加入那些其他表。查看查詢生成的SQL。希望這可以幫助!

+0

非常感謝...非常有幫助。 – user972255