我需要使用存储库模式和放大器连接多个表。实体框架(使用C#)。这可能吗?如果是这样,请告诉我如何做同样的事情。
答案 0 :(得分:6)
在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。希望这有帮助!