views:

31

answers:

2

I'm running into some issues when constructing a query using LINQ and Entity Framework.

My model is like this

Merchants(MerchantId)
    AffiliateFeeds(AffiliateFeedId, MerchantId)
        ProductSKUs(ProductId, AffiliateFeedId)

This snippet works well enough:

// only get Merchants and AffiliateFeeds based on specific ProductSKU.ProductId

var productSKUs = from ps in _context.ProductSKUs
                    where ps.ProductId == 38
                    select ps.AffiliateFeedId;

var feeds = from af in _context.AffiliateFeeds
            where productSKUs.Contains(af.AffiliateFeedId)
            select af;

var dm = (from f in feeds select f.MerchantId).Distinct();   

var merchants = from m in _context.Merchants
                where dm.Contains(m.MerchantId)
                select new 
                {
                    MerchantId = m.MerchantId,
                    Name = m.Name,
                    SysName = m.SysName,
                    DataFeedUrl = m.DataFeedUrl,
                    AffiliateFeeds = feeds.Where(x => x.MerchantId == m.MerchantId)
                };

However when I try and perform the projection into an Entity Framework generated class called Merchant as so:

var merchants = from m in _context.Merchants
                where dm.Contains(m.MerchantId)
                select new Merchant
                {
                    MerchantId = m.MerchantId,
                    Name = m.Name,
                    SysName = m.SysName,
                    DataFeedUrl = m.DataFeedUrl,
                    AffiliateFeeds = feeds.Where(x => x.MerchantId == m.MerchantId)
                };

I get an error stating:

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Data.Objects.DataClasses.EntityCollection'

A: 

You can't project onto EF types. You can project onto POCOs and anonymous types, but not onto EF-mapped types. The reason is that the EF will never partially materialize an instance of an entity.

Craig Stuntz
+2  A: 

Well, the error message itself is fairly clear: the property AffiliateFeeds is of type EntityCollection<SACore.AffiliateFeed> and you're trying to assign an arbitrary IQueryable<SACore.AffiliateFeed> to it.

Quite how to fix the problem is a different matter. I would expect that Where clause to effectively be automatic based on the entity definitions for the join between the tables.

Jon Skeet
Thanks :D I'm trying to iterate thru a list of Merchants and then iterate thru the associated AffiliateFeeds. If I do not project, when I iterate thre the feeds, the entire list of feeds is shown. It's like the constraints I applied were ignored. Would you know why this is?
sf
@sf: I don't have much experience of EF, but basically check the AffiliateFeeds/Merchant relation.
Jon Skeet