实体框架Linq查询 - 无法隐式转换System.Collection.Generic.List< AnonymousType#1> [英] Entity Framework Linq query - Cannot implicitly convert System.Collection.Generic.List<AnonymousType#1>

查看:69
本文介绍了实体框架Linq查询 - 无法隐式转换System.Collection.Generic.List< AnonymousType#1>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我是实体框架和Linq的新手。可以帮我解决下面的错误吗?

I am new to entity framework and Linq. Can please help me to resolve my error below?

我在下面的代码中收到编译错误消息:无法隐式转换System.Collection.Generic.List< AnonymousType#1>

I get compilation error message on code below : Cannot implicitly convert System.Collection.Generic.List<AnonymousType#1>

public List<ProductCategory> GetProducts()
    {
      var entity = new AdventureWorksLT2008Entities();
      
      var qry = from o in entity.ProductCategories
           group o by o.ParentProductCategoryID into g
           select new { g.Key , Count = g.Count() };

       return qry.ToList();
    }

Tq。

问候,

Carles

推荐答案

这是正确的。因为每当你执行 new {g.Key,Count = g.Count()} 时,它将创建一个匿名类型对象,但不会创建"Productcategory"对象。因此,施法无效。因此,您可以更新您的Linq查询,如下所示。

That's correct. Because whenever you do new { g.Key , Count = g.Count() } it will create an anonymous type objects but not 'Productcategory' object. Hence the casting is invalid. So, you can update your Linq query something as below.


public List<ProductCategory> GetProducts()
{
   var entity = new AdventureWorksLT2008Entities();
   
   var qry = from o in entity.ProductCategories
      group o by o.ParentProductCategoryID into g
      select new ProductCategory(){ Key = g.Key , Count = g.Count() };

    return qry.ToList();
}


这篇关于实体框架Linq查询 - 无法隐式转换System.Collection.Generic.List&lt; AnonymousType#1&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆