如何使用存储库模式和实体框架连接多个表?

use*_*255 8 c# repository-pattern entity-framework-4

我需要使用存储库模式和实体框架(使用C#)连接多个表.这可能吗?如果是这样,请告诉我如何做同样的事情.

Bai*_*ose 7

在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; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

对于多个表,您可以嵌套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
}
Run Code Online (Sandbox Code Playgroud)

一旦你包含了nav属性,那么基本上就是加入其他表.只需查看查询生成的SQL.希望这可以帮助!