我需要使用存储库模式和实体框架(使用 C#)连接多个表。这可能吗?如果是这样,请让我知道如何做同样的事情。
在 EF 中,连接表是通过使用导航属性完成的。基本上,EF 会为您做到这一点。在您的存储库中实现时,无论它是否是通用的,您都可以调用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
}
一旦包含导航属性,那么基本上就是连接其他表。只需查看查询生成的 SQL 即可。希望这可以帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)