【问题标题】:cannot implicitly convert type 'system.collections.generic.list<string> ' to 'system.collections.generic.list<entities.tablename>无法将类型“system.collections.generic.list<string>”隐式转换为“system.collections.generic.list<entities.tablename>
【发布时间】:2014-08-30 17:58:40
【问题描述】:

我尝试了几乎所有的解决方案,但没有用。我无法获得特定列优先级的不同列表。非常感谢任何帮助。

public List<AlertType> GetAllAlertNames()
        {
            var lstAlertNames = _zyenaDbContext.AlertTypes.Select(x => x.Priority).Distinct().ToList();

            return lstAlertNames;          
        }

返回 lstAlertNames 时出现以下错误:

cannot implicitly convert type 'system.collections.generic.list string '
 to 'system.collections.generic.list zyenaEntities.AlertType

在模型警报类型中

public string Priority { get; set; }

【问题讨论】:

    标签: entity-framework asp.net-mvc-4


    【解决方案1】:

    .Select(x =&gt; x.Priority) 只选择了Priority 属性(typeof string),因此您选择了List&lt;string&gt;,但您的方法返回了List&lt;AlertType&gt;

    不确定您真正想要返回什么,但如果是 List&lt;AlertType&gt; morelinq 有一个有用的扩展方法,可以让您执行 AlertTypes.DistinctBy(x =&gt; x.Priority);

    【讨论】:

    • 是的,刚刚在这里找到它:stackoverflow.com/questions/4607485/…
    • 是的@stepehen Muecke 优先级返回字符串。我的应用程序的实体框架中的智能感知不支持 DistinctBy。
    • 但是如果我没记错的话,morelinq 不会在 linq to entity 上工作。它专用于 linq to objects...
    • 我想我应该使用 nuget 包安装 morelinq。让我试试看。
    • @RaphaëlAlthaus 感谢您的回复....但是您如何区分 linq 到实体和 linq 到对象。这是我收集信息的一般问题,因为我不知道区别。
    【解决方案2】:

    主要错误是我试图仅返回实体 AlertType 无法转换的单个属性 Priority。

    public List<string> GetDistinctAlertPriorities()
            {
    
                var lstAlertNames = _zyenaDbContext.AlertTypes.Select(x => x.Priority).Distinct().ToList();
                return lstAlertNames;
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      相关资源
      最近更新 更多