繁体   English   中英

具有引用属性的实体的Linq

[英]Linq to Entities with a referenced property

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

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

在同一情况下,我们使用以下代码:

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)
        }
    }
}

在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);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM