具有实体框架和WebApi的计算属性

时间:2018-04-06 14:06:00

标签: c# entity-framework asp.net-web-api entity-framework-6

如何在EF模型中正确处理计算属性?

我的尝试将失败,因为"实体或复杂类型'发票'无法在LINQ to Entities查询中构造。"

考虑方法" GetInvoice"作为带有允许查询字符串的WebApi方法。

static void Main(string[] args)
{
        var invs = GetInvoice();

        invs.FirstOrDefault();

}

public static IQueryable<Invoice> GetInvoice()
{
        var model = new Model();

        IQueryable<Invoice> inv = model.Invocies.Include(t => t.Items).SelectInvoiceData();
        return inv;
}

public static class ExtHelper
{
    public static IQueryable<Invoice> SelectInvoiceData(this IQueryable<Invoice> item)
    {
        return item.Select(c => new Invoice
        {
            LatestItemName = c.Items.FirstOrDefault().Name
        });
    }
}

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CreatedAt { get; set; }
}

public class Invoice
{
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; }

    public string Issuer { get; set; }

    [NotMapped]
    public string LatestItemName { get; set; }

    private ICollection<Item> _items;
    public virtual ICollection<Item> Items
    {
        get { return _items ?? (_items = new Collection<Item>()); }
        set { _items = value; }
    }

}

1 个答案:

答案 0 :(得分:1)

EntityFramework 6不支持像这样创建部分实体。使用匿名类型:

return item.Select(c => new
{
    LatestItemName = c.Items.FirstOrDefault().Name
});

或某些不属于上下文的DTO类:

return item.Select(c => new InvoiceDTO
{
    LatestItemName = c.Items.FirstOrDefault().Name
});

然而,在EF Core中,可以像您的示例中那样创建实体。