0

我正在使用 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
        }
    }
}

对于这个问题还有其他更好的解决方案吗?

4

2 回答 2

1

在 DbSet 中使用Find方法

public class MasterDataViewModel<T> :  where T : IDBEntity, new()
{
    public T CurrentItem { get; set; }

    public void ReloadItem(int id)
    {
        using (var context = new DatabaseContext())
        {
            CurrentItem = context.Set<T>().Find(id);
        }
    }
}
于 2013-10-02T10:40:52.237 回答
1

在同样的情况下,我们使用了以下代码:

public class BaseEntity
{
    public int Id { get; set; }
}

所以你的Product会看起来像

public class Product : BaseEntity
{    
    public string Name { get; set; }
}

MasterDataViewModel

public class MasterDataViewModel<T> :  where T : BaseEntity, new()
{
    public T CurrentItem { get; set; }

    public void ReloadItem(int id)
    {
        using (var context = new DatabaseContext())
        {
            CurrentItem = context.Set<T>.FirstOrDefault(x => x.Id == id)
        }
    }
}
于 2013-10-02T10:34:39.837 回答