在Linq中将类转换为同一类的部分

时间:2014-04-02 14:22:02

标签: c# linq entity-framework casting

我在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();

但是得到:

  

无法播放类型&#39;匿名类型&#39;输入&#39; Meha3.Models.Tree&#39;。   LINQ to Entities仅支持转换EDM原语或枚举   类型

4 个答案:

答案 0 :(得分:2)

你要求的是&#34; Duck&#34;打字和.Net不支持&#34; Duck&#34;打字,这样你就无法直接投射。您的所有选项都包括通过映射,树上的构造函数,反射等将其转换为您想要的类型,但实际的转换是不可能的。

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

Conversion option here

Reflection option here

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

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

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

由于匿名类型不属于Type Tree,因此无法从anoymous类型转换为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();

答案 3 :(得分:0)

你可以使用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();