2012-08-22 39 views
0

在LINQ2SQL,有可能做一个查询,如:实体框架嵌套查询拉姆达

using (var db = GetDataContent()) 
      { 
       var query = from p in db.Brands 
          where p.Deleted == false 
          select new BrandImageSummary 
          { 
           BrandID = p.BrandID, 
           BrandUrl = p.BrandUrl, 
           Description = p.Description, 
           MetaDescription = p.MetaDescription, 
           MetaKeywords = p.MetaKeywords, 
           MetaTitle = p.MetaTitle, 
           BrandImageUrl = (from p2 in db.SiteImages where p2.FileTypeID == 5 && p2.ForeignID == p.BrandID && p2.Deleted == false orderby p2.Rank select p2.Filename).FirstOrDefault(), 
           Deleted = p.Deleted, 
           SupplierCode = p.SupplierCode, 
           Title = p.Title, 
           Website = p.Website 
          }; 

       return query.ToList(); 
      } 

随着BrandImageUrl是一个嵌套的选择。 HOWVER在实体框架中,我似乎得到的错误:

Unable to create a constant value of type 'SiteImage'. Only primitive types or enumeration types are supported in this context.

有没有办法在实体框架中做到这一点?

查询的想法是获得一个品牌形象,如果我要加入,并有多个图像,我会得到多行,我不想这样。

我使用实体框架5.

感谢您的帮助

回答

1

你应该建立在你的模型类一个一对多的关系。

然后,您可以编写

BrandImageUrl = p.BrandImages 
       .Where(i => i.FileTypeID == 5 && !i.Deleted) 
       .OrderBy(i => i.Rank) 
       .Select(i => i.FileName) 
       .FirstOrDefault() 
+0

感谢这个,但有现在这样的方式,没有设置参考的?我试图将应用程序移植到实体框架,并且有很多很多很多的查询。 – user614143