简体   繁体   中英

Computed Properties with Entity Framework and WebApi

How to correctly handle computed properties in EF model?

My try bellow will fail because of "The entity or complex type 'Invoice' cannot be constructed in a LINQ to Entities query."

Consider method "GetInvoice" as WebApi method with allowed querystring.

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. Either use anonymous type:

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

Or some DTO class that does not belong to context:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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