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<Customer> Customers { get; set; } public virtual DbSet<Order> Orders { get; set; } public IQueryable<T> GetAllIncluding<T>(params Expression<Func<T, object>>[] include) where T : class { var retVal = this.Set<T>(); 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<Order> Orders { get; set; } public Customer() { Orders = new List<Order>(); }
}
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<Customer>(c => 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);