开发者

ef cf linq populate ignored property

I'm sure this has to have been asked before, but I couldn't find a good way to search on it.

I have a class like the following

public class Vendor
{
    public int VendorId { get; set; }
    public string Name { get; set; }
    public int ProductCount { get; set; }
}

I have a configuration class setup like

public class VendorConfiguration : EntityTypeConfiguration<Vendor>
{
    public VendorConfiguration()
    {
        Property(p => p.Name).IsRequired().HasMaxLength(128);
        Ignore(v => v.ProductCount);
    }
}

Here is the query i u开发者_高级运维se to grab the vendors.

    public Vendor[] GetVendors()
    {
        using (var db = new UbidContext())
        {
            var query = (from vendor in db.Vendors
                                        select vendor);

            return query.ToArray();
        }
    }

How could I populate ProductCount with a subquery that would look similar to

ProductCount = (from vend in db.VendorProducts
 where vend.VendorId == id
 select vend).Count()

Is there a way I can add that to the main query, so I'm only making 1 call to the db?

Thanks, Andrew


I would try it this way:

public Vendor[] GetVendors()
{
    using (var db = new UbidContext())
    {
        var query = from vendor in db.Vendors
                    join vp in db.VendorProducts
                        on vendor.VendorId equals vp.VendorId
                    into vendorProducts
                    select new
                    {
                        Vendor = vendor,
                        ProductCount = vendorProducts.Count()
                    };

        foreach (var item in query)
            item.Vendor.ProductCount = item.ProductCount;

        return query.Select(a => a.Vendor).ToArray();
    }
}

Problem is that you must project into a non-entity type (anonymous in the example above) and then copy the projected ProductCount value into the projected Vendor item by item before you return it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜