C# 如何在实体数据上下文中使用Func?
我在下面写了代码MyCustomer.cs必须返回客户实体类型的列表。İ采用Func方法。我想这样做:C# 如何在实体数据上下文中使用Func?,c#,.net,visual-studio,linq,entity-framework,C#,.net,Visual Studio,Linq,Entity Framework,我在下面写了代码MyCustomer.cs必须返回客户实体类型的列表。İ采用Func方法。我想这样做: return erpEntityCtx.Customer.Select(select).ToList<TResult>(); List<TResult> Load<TKey, TResult>(Func<TKey, TResult> select) { using (Erp.DAL.ErpEntities erpEntityCt
return erpEntityCtx.Customer.Select(select).ToList<TResult>();
List<TResult> Load<TKey, TResult>(Func<TKey, TResult> select)
{
using (Erp.DAL.ErpEntities erpEntityCtx = new Erp.DAL.ErpEntities())
{
return erpEntityCtx.Customer.Select(select).ToList<TResult>();
}
}
但是,请返回给我:
有一些无效的论点
我可以用这个:
return erpEntityCtx.Customer.Select(c=>c.Name).ToList<TResult>();
但是,我不能用DataContext实现这一点,我如何实现这一点
public class MyCustomer : Manager.ILoad
{
#region ILoad Members
public List<TResult> Load<TKey, TResult>(Func<TKey, TResult> select)
{
using (Erp.DAL.ErpEntities erpEntityCtx = new Erp.DAL.ErpEntities())
{
return erpEntityCtx.Customer.Select(select).ToList<TResult>();
}
}
#endregion
}
我认为您最初的问题之一是您的ILoad接口是非泛型的,但是您已经指定了没有泛型约束的方法,例如
List<TResult> Load<TKey, TResult>(Func<TKey, TResult> select);
如果不在泛型方法或更好的泛型类上指定任何约束,就无法用Func满足Func
您可能需要对此进行更改:
public interface IRepository<TModel>
{
List<TModel> Get(Func<TModel, bool> predicate);
}
并实施为:
public class CustomerRepository : IRepository<Customer>
{
public List<Customer> Get(Func<Customer, bool> predicate)
{
using (var context = new ErpEntities())
{
return context.Customers.Where(predicate).ToList();
}
}
}
您应该了解存储库模式。但我该怎么做:public List getirepositionary erpObj,Func predicate{return erpObj.Getpredicate;}我想在我的问题中从上面的管理器类中进行控制?为什么需要在上面保持分层?
public class CustomerRepository : IRepository<Customer>
{
public List<Customer> Get(Func<Customer, bool> predicate)
{
using (var context = new ErpEntities())
{
return context.Customers.Where(predicate).ToList();
}
}
}