c# - linq to entities 无法将类型 Icollection 转换为类型 List

标签 c# linq entity-framework

我正在使用 Entity Framework 。 我有以下实体:

public class Articolo
{
    ..
    public virtual ICollection<Fornitore> Fornitori { get; set; }
}

public class Fornitore
{
  ...
   public virtual ICollection<Articoli> Articoli { get; set; }    }

以下代码:

List<Fornitore> result = new List<Fornitore>();
var r = zefiroContext.Articoli.Where(p => p.Id == IdArticolo).Select(p => p.Fornitori).ToList();
result = r;

给出一个编译器错误:

Cannot implicitly convert type 'System.Collections.Generic.List < System.Collections.Generic.ICollection < prova2.Model.Fornitore>>' to 'System.Collections.Generic.List < prova2.Model.Fornitore>'

我怎样才能得到我的 List < Fornitore >

最佳答案

好吧,您实际上是在尝试选择多个集合,我认为这就是您的问题所在,将 Select 更改为 SelectMany 可能会为您解决问题,但我不确定这是否是您的预期功能。将要发生的是 SelectMany 会将所有单独的结果集压缩到一个集合中,然后可以将该集合转换为模型类型的列表与模型类型的集合列表。

var r = zefiroContext.Articoli.Where(p => p.Id == IdArticolo).SelectMany(p => p.Fornitori).ToList();

关于c# - linq to entities 无法将类型 Icollection 转换为类型 List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13241934/

相关文章:

asp.net-mvc - 如何创建具有多个模型 mvc 4 的 View ?

c# - 用 DynamicObject 替换静态资源属性

c# - 解释这个 LINQ 代码?

c# - 如何将枚举值序列化为字符串?

Linq 失败而不是返回 null?

c# - 如何在 LINQ 查询中按月分组?

c# - 使用聚合和分组依据的 LINQ 查询

c# - 在c# Winform( Entity Framework )中搜索记录

c# - 在WPF C#中将GridView与字典绑定(bind)

C# : Make a property for a variable with a different name (shortcut)?