【问题标题】:How to join Multiple tables using Repository Pattern & Entity Framework?如何使用存储库模式和实体框架连接多个表?
【发布时间】:2014-01-04 13:23:40
【问题描述】:

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

【问题讨论】:

    标签: c# entity-framework-4 repository-pattern


    【解决方案1】:

    在 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 的示例代码 sn-p:

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

    对于多个表,您可以像这样嵌套包含方法:

    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。希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多