LINQ投影到ADO.Net Entity Framework类时的类型转换问题

时间:2010-08-23 17:47:31

标签: linq entity-framework

使用LINQ和Entity Framework构建查询时遇到了一些问题。

我的模特就像这样

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

此代码段效果不错:

// 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)
                };

然而,当我尝试将实体投影到Entity Framework生成的类中时,执行如下:

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)
                };

我收到错误声明:

  

无法隐式转换类型   'System.Linq.IQueryable'   至   'System.Data.Objects.DataClasses.EntityCollection'

2 个答案:

答案 0 :(得分:2)

嗯,错误消息本身非常清楚:属性AffiliateFeeds的类型为EntityCollection<SACore.AffiliateFeed>,您尝试为其分配任意IQueryable<SACore.AffiliateFeed>

如何修复问题是另一回事。我希望Where子句能够根据表之间连接的实体定义自动生成。{/ p>

答案 1 :(得分:0)

您无法投影到EF类型。您可以投影到POCO和匿名类型,但不能投影到EF映射类型。原因是EF永远不会部分实现实体的实例。