如何使用存储库模式和entity framework连接多个表?

我需要使用存储库模式和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 DogList { get; set; } public ICollection CatList { get; set; } } 

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

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

对于多个表,您可以嵌套include方法,如下所示:

 public virtual IEnumerable 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。 希望这可以帮助!