我正在使用 EF 5.0 做一个带有主数据管理的应用程序,我希望它尽可能通用,因为加载项目、保存项目等总是相同的。
我的实体看起来像这样:
// IDBEntity.cs
public interface IDBEntity<T>
{
public int ID { get; }
...
}
// Product.cs (Generated)
public class Product
{
public int ProductID
{
get; set;
}
public string Name
{
get; set;
}
}
// ProductExtension.cs
public patial class Product : IDBEntity<Product>
{
public int ID
{
get
{
return ProductID
}
}
}
现在我想在某些情况下查询 ID,但问题是您不能使用自定义属性执行 LINQ to Entity 查询。
public class MasterDataViewModel<T> : where T : IDBEntity, new()
{
public T CurrentItem { get; set; }
public void ReloadItem(int id)
{
using (var context = new DatabaseContext())
{
// This is the problem
CurrentItem = context.Set<T>.FirstOrDefault(x => x.ID == id)
}
}
}
是否可以使用指向真实 ID 的表达式来执行此操作?像这样的东西:
public interface IDBEntity<T>
{
public Expression<Func<T, int>> { get; }
}
public patial class Product : IDBEntity<Product>
{
public Expression<Func<Product, int>> ID
{
get
{
return x => x.ProductID
}
}
}
对于这个问题还有其他更好的解决方案吗?