【问题标题】:Cast class to partial of same class in Linq将类转换为 Linq 中同一类的部分
【发布时间】:2014-04-02 23:20:00
【问题描述】:

我在 EF 中作为实体的类是:

Cat { Id, ParentId, Name, ImageUrl, ...}

Tree { Id , ParentId, Name}

还有其他选择吗:

var trees= (from rs in _db.ItemCats
            where rs.ParentId == null
            select new Tree
            {
                Id = rs.Id,
                ParentId = rs.ParentId,
                Name = rs.Name
            }).ToList();

类似:

var trees= (from rs in _db.ItemCats
            where rs.ParentId == null
            select new 
            { 
                rs.Id, rs.Name, 
                rs.ParentId 
            }).Cast<Tree>().ToList();

但是得到:

无法将类型“匿名类型”转换为类型“Meha3.Models.Tree”。 LINQ to Entities 仅支持转换 EDM 原语或枚举 类型

【问题讨论】:

标签: c# linq entity-framework casting


【解决方案1】:

您要求的是“Duck”类型,而 .Net 不支持“Duck”类型,因此您无法直接投射。您的所有选项都包括通过映射、树上的构造函数、反射等将其转换为您想要的类型,但实际的转换是不可能的。

申请其他 SO 答案的链接,但我认为不需要在此处复制详细信息...

Conversion option here

Reflection option here

Yet another way by Skeet 他特别说这太可怕了...不要这样做...

我强烈推荐使用转换方法或构造方法。

【讨论】:

  • tnx 很多亲爱的@Kevin
【解决方案2】:

是的,有。但是,不像你的例子。您可能想查看Automapper

如果您使用它,您的问题将像这样解决:

Mapper.CreateMap<Cat, Tree>();
var tree = Mapper.Map<Tree>(cat);

【讨论】:

  • tnx 但没有 Automapper
【解决方案3】:

你不能从匿名类型转换为 Tree 类,因为匿名类型不是树类型

您还违反了关于服务器端可以执行和不可以执行的各种 EF 规则

当我不得不执行类似的任务时,我最终不得不编写这样的代码 - 不优雅,但它有效:

var trees= (from rs in _db.ItemCats
        where rs.ParentId == null
        select new 
        { 
            Id = rs.Id, 
            Name = rs.Name, 
            ParentId = rs.ParentId 
        })
        .AsEnumerable() //to run the query and take us out of the EF domain
        .Select(a => new Tree()
        {
           Id = a.Id,
           Name = a.Name,
           ParentId = a.ParentId
        })
        .ToList();

【讨论】:

  • 问题中的代码(没有演员表的版本)工作得很好。没有必要这样做。他只是想让它更短/更简单。这恰恰相反。
【解决方案4】:

您可以使用 Lambada 语法将其缩短一点,但不多

类似这样的:

var trees= _db.ItemCats.Select(Cat => new Tree(){
            Id = Cat.Id,
            ParentId = Cat.ParentId,
            Name = Cat.Name
        }).ToList();

另一个选择是,如果您经常这样做,您可以将转换移动到允许您调用类似这样的扩展方法

var trees = _db.ItemCats.Select(Cat => Cat.ToTree()).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2015-04-25
    相关资源
    最近更新 更多