Type conversion issues when LINQ projecting into ADO.Net Entity Framework class
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)
sele开发者_JAVA技巧ct 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'
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.
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.
精彩评论