简体   繁体   English

使用实体框架和WebApi计算属性

[英]Computed Properties with Entity Framework and WebApi

How to correctly handle computed properties in EF model? 如何正确处理EF模型中的计算属性?

My try bellow will fail because of "The entity or complex type 'Invoice' cannot be constructed in a LINQ to Entities query." 由于“无法在LINQ to Entities查询中构造实体或复杂类型'发票',我的尝试失败了。”

Consider method "GetInvoice" as WebApi method with allowed querystring. 将方法“ 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; }
    }

}

EntityFramework 6 does not support creating partial entities like this. EntityFramework 6不支持创建这样的部分实体。 Either use anonymous type: 可以使用匿名类型:

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

Or some DTO class that does not belong to context: 或一些不属于上下文的DTO类:

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

However in EF Core it is possible to create entities like in your example. 但是,在EF Core中,可以像您的示例中那样创建实体。

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

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