【问题标题】:solve convert problem from one entity to another?解决从一个实体到另一个实体的转换问题?
【发布时间】:2020-01-18 15:39:23
【问题描述】:
var i = SectionRepository.GetAll().OrderBy(x => x.Name).GroupBy(x => x.Category).OrderBy(x => x.Key.Name);
 var b = (IOrderedEnumerable<IGrouping<TaggedEntity, TaggedEntity>>)i;

无法转换类型的对象 'System.Linq.OrderedEnumerable2[System.Linq.IGrouping2[Prj.Core.Domain.Category,Prj.Core.Domain.Section],System.String]' 输入 'System.Linq.IOrderedEnumerable1[System.Linq.IGrouping2[Prj.Core.Common.TaggedEntity,Prj.Core.Common.TaggedEntity]]'。

大家好。请帮帮我。从 TaggedEntity 继承的部分和类别。转换过程中发生错误。 项目正在使用 .net 4 和 asp mvc 4。我如何转换这些实体?

【问题讨论】:

  • 请分享其余代码和您的实体

标签: c# asp.net linq


【解决方案1】:

您不能将子类转换为其父类。

你需要为父类使用某种接口,例如

public interface ITaggedItem {
    string Tag {get;set;}
}

public class TaggedItem: ITaggedItem {
    public string Tag {get;set;}
}

public class Category: TaggedItem{
}

var b = (IOrderedEnumerable<IGrouping<ITaggedEntity, ITaggedEntity>>)i;

【讨论】:

    【解决方案2】:

    您可以将CategorySection 转换为TaggedEntity,因为两者都是从它派生的,但IGrouping&lt;Category, Section&gt;IGrouping&lt;TaggedEntity, TaggedEntity&gt; 是完全不同的类型。
    而是在构建预期集合之前显式转换每个值

    var orderedGroups = SectionRepository.GetAll()
        .OrderBy(section => section.Name)
        .GroupBy(section => (TaggedEntity)section.Category, section => (TaggedEntity)section)
        .OrderBy(group => group.Key.Name); // Hope "Name" is the part of TaggedEntity type
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多