【问题标题】:Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<Model.Common.Province>'l C# MVc无法将类型“System.Collections.Generic.List<AnonymousType#1>”隐式转换为“System.Collections.Generic.List<Model.Common.Province>”l C# MVc
【发布时间】:2017-04-09 10:30:47
【问题描述】:

我的代码在下面

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;

我想在表格中显示简单并加入国家以在表格中显示国家名称。错误如下

错误 6 无法隐式转换类型 'System.Collections.Generic.List' 到 'System.Collections.Generic.List'

public class Province
{
    [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<Country> CountryCollection { get; set; }
}

【问题讨论】:

  • 你能展示你的省级吗?我不认为它被映射到正确的类型!使用 var 并查看悬停时建议的预期输出类型。
  • @touchofevil public class Province { [Key] public int ProvinceID { get;放; } [必需] public int CountryID { get;放; } [必需] 公共字符串省名 { 获取;放; } 公共字符串描述 { 获取;放; } [NotMapped] public List CountryCollection { get;放; } }
  • 您需要创建一个包含ProvinceCountry 属性的视图模型,然后使用select new YourViewModel { ... }
  • @UmerZaman - 请不要在 cmets 中放置课程 - 您应该编辑您的问题。

标签: c# asp.net-mvc linq


【解决方案1】:

从错误中可以清楚地看出,您无法将 anonymous 类型转换为 generic 类型,并且使用域模型的方式不正确,因此您应该创建另一个名为 ViewModel 的类,该类用于特定查看您的情况,您需要country nameprovince,所以您的ViewModel 将是

public class ProvinceCountryViewModel
    {
         public int ProvinceID { get; set; }
         public string ProvinceName { get; set; }
         public string CountryName { get; set; }
    }

您的linq 将是

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;

view

 @foreach (var value in  (List<ProvinceCountryViewModel>) ViewBag.Province )
    {

      // here you can access properties like value.CountryName 

    }

【讨论】:

    【解决方案2】:

    LINQ中使用select时,需要创建新的Province类实例,而不是匿名对象。

    select new Province{ /*assign properties here*/ }).ToList();
    

    【讨论】:

    • 这将引发错误。而Province 模型不包含名为CountryName的属性
    • 这里我只能选择省项目,但也想选择国家
    • 查看 OP 对 Marcus H 的回答的评论
    【解决方案3】:

    如下所述返回省份类型

     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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 2011-05-14
      相关资源
      最近更新 更多