C# 使用LINQ SQL的模板/通用方法?
我有一个类,它从我的数据库为客户创建数据访问函数:C# 使用LINQ SQL的模板/通用方法?,c#,.net,linq,C#,.net,Linq,我有一个类,它从我的数据库为客户创建数据访问函数: public static Customer Get(int ID) { KezberPMDBDataContext db = new KezberPMDBDataContext(); return (from p in db.Customers where p.CustomerID == ID select p).FirstOrDefa
public static Customer Get(int ID)
{
KezberPMDBDataContext db = new KezberPMDBDataContext();
return (from p in db.Customers
where p.CustomerID == ID
select p).FirstOrDefault();
}
public static bool Remove(int ID)
{
Customer c = Get(ID);
if (c != null)
{
KezberPMDBDataContext db = new KezberPMDBDataContext();
db.Customers.DeleteOnSubmit(c);
db.SubmitChanges();
return true;
}
return false;
}
我将创建更多的类,例如Employees,它们将需要完全相同的功能,只需要Employees类
是否有某种方法可以避免代码重复并以某种方式使用模板/泛型
感谢EntityFramework 4.3和5的类有一个方法,该方法完全执行Get方法的操作,还有一个方法执行Remove方法的操作,它接受对象而不是id。您可以执行以下操作:
private T GetById(int id, IQueryable<T> list)
{
var itemParameter = Expression.Parameter(typeof(T), "item");
var whereExpression = Expression.Lambda<Func<T, bool>>
(
Expression.Equal(
Expression.Property(
itemParameter,
PrimaryKeyName
),
Expression.Constant(id)
),
new[] { itemParameter }
);
var item = list.Where(whereExpression).SingleOrDefault();
if (item == null)
{
throw new PrimaryKeyNotFoundException(string.Format("No {0} with primary key {1} found",
typeof(T).FullName, id));
}
return item;
}
是Linq到Sql还是实体框架?如果是EF,那么是什么版本?在这两种情况下,我建议您在谷歌上实现通用存储库模式