gpt4 book ai didi

c# - 无法将类型隐式转换为“System.Collections.Generic.List”

转载 作者:太空狗 更新时间:2023-10-30 00:40:20 25 4
gpt4 key购买 nike

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

View 模型:

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

但是,我遇到了错误:

Error 1 Cannot implicitly convert type
System.Data.Entity.DbSet<tb.Models.TourCategory> to
System.Collections.Generic.List<tb.Models.ViewModels.TourCategoryList>

是我的 ViewModel 错了吗?

最佳答案

db.TourCategories()方法不返回 TourCategoryList 的集合, 所以你必须做更多的工作来转换任何类 TourCategories()返回到 TourCategoryList , 使用 LINQ Select()方法。

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

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


如果我能提出其他建议,您可能想重命名 TourCategoryList .我知道你想把它和其他的区分开来TourCategory类,但查看您的代码的人可能会(乍一看)认为 List<TourCategoryList>是列表的列表,只是从名字上看。

关于c# - 无法将类型隐式转换为“System.Collections.Generic.List”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28632103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com