How is the method to include() in Repository?



  • In the construction of the application, use the patent Repository. Repository interface:

    public interface IShopContext
    {
        IQueryable<T> GetAllIncluding<T>(params Expression<Func<T, object>>[] include) where T : class;
    }
    

    Implementation of the interface in the context of EF:

    public class ShopContext : DbContext, IShopContext
    {
        public ShopContext()
            : base("name=ShopDB")
        {
        }
    
    public virtual DbSet&lt;Customer&gt;    Customers { get; set; }
    public virtual DbSet&lt;Order&gt;      Orders { get; set; }
    
    public IQueryable&lt;T&gt; GetAllIncluding&lt;T&gt;(params Expression&lt;Func&lt;T, object&gt;&gt;[] include) where T : class
    {
        var retVal = this.Set&lt;T&gt;();
    
        foreach(var item in include)
        {
            retVal.Include(item);
        }
    
        return retVal;
    
    }
    

    }

    Use the CodeFirst approach. The base is generated. In SQL SMS 2014, the link between Customers-Orders : One-to-Many and visible on diagram. The table is available.

    Классы сущностей:

    public class Customer
    {
    public int CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Patronymic { get; set; }

    public ICollection&lt;Order&gt; Orders { get; set; }
    
    public Customer()
    {
        Orders = new List&lt;Order&gt;();
    }
    

    }

    public class Order
    {
    public int OrderId { get; set; }
    public string Number { get; set; }
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
    }

    Test code

    [TestInitialize]
    void Initialize()
    {
    con = new ShopContext();
    }

    [TestMethod]
    public void Query_GetCustomersListIncluding_NoExc()
    {
    Initialize();

    var l = con.GetAllIncluding&lt;Customer&gt;(c =&gt; c.Orders).ToList();
    
    foreach (var item in l)
    {
        Trace.TraceInformation($"{item.LastName}");
        foreach (var i in item.Orders)
        {
            Trace.TraceInformation($"{i.Number}");
        }                
    }
    

    }

    The problem is, this test only gives out the name of the customers, but doesn't take orders. At the debage, it was discovered that the variables should contain a link to the object with the collection of orders, empty. What's the problem?



  • The mistake is:

    retVal.Include(item);
    

    Must be:

    retVal = retVal.Include(item);
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2