如何加入多个表使用存储库模式和放大器;实体框架? [英] How to join Multiple tables using Repository Pattern & Entity Framework?

查看:102
本文介绍了如何加入多个表使用存储库模式和放大器;实体框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用存储库模式和放大器来连接多个表;实体框架(使用C#)。这可能吗?如果是这样,请让我知道该怎么做。

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.

推荐答案

在EF,连接表是通过使用导航完成属性。基本上,EF会为你。当你的存储库实施,可以说,它是通用与否,你可以调用的包括方法。

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.

让我们说我们有这些POCO类:

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
}

一旦你包括导航性能,然后将其加入基本上与其他表。试想一下,在SQL查询所生成。希望这有助于!

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!

这篇关于如何加入多个表使用存储库模式和放大器;实体框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆