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

只谈情不闲聊 提交于 2019-11-30 15:07:46

问题


I need to join multiple tables using repository pattern & Entity Framework (using C#). Is this possible? If so, please let me know how to do the same.


回答1:


In EF, joining tables is done through the use of Navigation Properties. Basically, EF does it for you. When implementing in your Repositories, may it be Generic or not, you can call the Include method when building your query expression to tell EF to populate the navigation properties for you.

Let's say we have these POCO class:

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; }
}

Here's a sample code snippet using Include:

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

And for multiple tables you can nest the include method like so:

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
}

Once you include nav properties then that is basically joining those other tables. Just look at the SQL being generated by the query. Hope this helps!



来源:https://stackoverflow.com/questions/20623022/how-to-join-multiple-tables-using-repository-pattern-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!