C# 无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”l C MVc
我的代码在下面C# 无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”l C MVc,c#,asp.net-mvc,linq,C#,Asp.net Mvc,Linq,我的代码在下面 List<Province> ldb = (from k in db.Provinces join c in db.Countrys on k.CountryID equals c.CountryID select new { k.ProvinceID, k.ProvinceName, c.CountryName }).ToList(); ViewBag.Province = ld
List<Province> ldb = (from k in db.Provinces
join c in db.Countrys on k.CountryID equals c.CountryID
select new { k.ProvinceID, k.ProvinceName, c.CountryName }).ToList();
ViewBag.Province = ldb;
我希望在表中显示简单,并与country关联以在表中显示国家名称。错误如下
错误6无法隐式转换类型
“System.Collections.Generic.List”到
'System.Collections.Generic.List'
返回省类型,如下所述
List<Province> ldb = (from k in db.Provinces
join c in db.Countrys on k.CountryID equals c.CountryID
select new Province { k.ProvinceID, k.ProvinceName, c.CountryName }).ToList();
ViewBag.Province = ldb;
在LINQ中使用select时,需要创建新的省级实例,而不是匿名对象
select new Province{ /*assign properties here*/ }).ToList();
从错误中可以清楚地看出,您无法将匿名类型转换为泛型类型,并且在视图中使用域模型的方式不正确,因此您应该创建另一个名为ViewModel的类。该类用于特定视图。在您的情况下,您需要国家名称和省,因此您的ViewModel将 而你的linq将会是
你能给我看一下你的班级吗?我认为它没有被映射到正确的类型!使用var并查看悬停时建议的预期输出类型。@touchofevil公共类ProvinceID{[Key]public int ProvinceID{get;set;}[Required]public int CountryID{get;set;}[Required]public string ProvinceName{get;set;}public string Description{get;set;}[NotMapped]public List CountryCollection{get;set;}}您需要创建一个视图模型,其中包含您想要的省和国家的属性,然后使用select new YourViewModel{…}@UmerZaman-请不要将类放在注释中-您应该编辑您的问题。这将引发错误。省模型不包含名为CountryName的属性在这里,我只能选择省项目,但也要选择countrySee OP对Marcus H答案的评论
select new Province{ /*assign properties here*/ }).ToList();
public class ProvinceCountryViewModel
{
public int ProvinceID { get; set; }
public string ProvinceName { get; set; }
public string CountryName { get; set; }
}
List<ProvinceCountryViewModel> ldb = (from k in db.Provinces
join c in db.Countrys on k.CountryID equals c.CountryID
select new ProvinceCountryViewModel{ProvinceID = k.ProvinceID, ProvinceName=k.ProvinceName,CountryName = c.CountryName }).ToList();
ViewBag.Province = ldb;
@foreach (var value in (List<ProvinceCountryViewModel>) ViewBag.Province )
{
// here you can access properties like value.CountryName
}