【问题标题】:Cannot implicitly convert type to 'System.Collections.Generic.List无法将类型隐式转换为 'System.Collections.Generic.List
【发布时间】:2015-02-20 23:28:25
【问题描述】:

我想用 DateTime 属性和类别列表填充视图模型。

视图模型:

public class TourCategoryVM
{
    public DateTime Date { get; set; }
    public List<TourCategoryList> TourCategoryList { get; set; }
}

public class TourCategoryList
{
    public int TourCategoryId { get; set; }
    public string TourType { get; set; }
}

领域模型:

public class TourCategory
{
    public int TourCategoryId { get; set; }
    public string TourType { get; set; }
    public virtual ICollection<Tour> Tour { get; set; }
}

我认为我可以使用以下代码轻松填充它:

        var viewModel = new TourCategoryVM();
        viewModel.TourCategoryList = db.TourCategories();

但是,我收到了错误:

错误 1 ​​无法隐式转换类型
System.Data.Entity.DbSet&lt;tb.Models.TourCategory&gt;
System.Collections.Generic.List&lt;tb.Models.ViewModels.TourCategoryList&gt;

是我的 ViewModel 有问题吗?

【问题讨论】:

  • 尝试将 .tolist() 添加到您的 db.tourcategories() 中
  • 谢谢马特 - 我试过了,但得到:不可调用的成员 'tb.Models.tbContext.TourCategories' 不能像方法一样使用
  • 将来可以使用反引号“`”来包围包含&lt;SomeClass&gt;但不在代码块中的文本,如果您不认为它们是,网站会将它们删除html标签。

标签: c# asp.net-mvc asp.net-mvc-4


【解决方案1】:

db.TourCategories() 方法不会返回 TourCategoryList 的集合,因此您需要做更多的工作才能使用 LINQ 的 Select() 方法将 TourCategories() 返回的任何类转换为 TourCategoryList .

viewModel.TourCategoryList = db.TourCategories()
                               .Select(tc => new TourCategoryList
                                             {
                                                 TourCategoryId = tc.TourCategoryId,
                                                 TourType = tc.TourType
                                             })
                               .ToList();

我假设TourCategories() 返回TourCategory 的集合。


如果我可以提出其他建议,您可能想要重命名 TourCategoryList。我知道您正试图将它与其他 TourCategory 类区分开来,但查看您的代码的人可能会假设(乍一看)List&lt;TourCategoryList&gt; 是列表列表,仅从名称。

【讨论】:

  • TourCategoryModel 是不同类名的常规选择。
  • 感谢格兰特 - 我这样做了,并将 TourCategoryList 重命名为 TourCategoryModel - 但现在出现另一个错误:无法在 LINQ to Entities 查询中构造实体或复杂类型“tb.Models.TourCategoryModel”。所以我在 dbTourCategories() 之后添加了 .ToList() 并且它起作用了!非常感谢你的帮助。标记
猜你喜欢
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 2019-01-03
  • 1970-01-01
相关资源
最近更新 更多