簡體   English   中英

如何使用存儲庫模式和實體框架連接多個表?

[英]How to join Multiple tables using Repository Pattern & Entity Framework?

我需要使用存儲庫模式和實體框架(使用C#)連接多個表。 這可能嗎? 如果是這樣,請告訴我如何做同樣的事情。

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

假設我們有這些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; }
}

以下是使用Include的示例代碼段:

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

對於多個表,您可以嵌套include方法,如下所示:

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
}

一旦你包含了nav屬性,那么基本上就是加入其他表。 只需查看查詢生成的SQL。 希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM