c# - 我们可以在 C# 中使用 Linq toentity 将匿名类型转换为 List <T> 吗?

标签 c# linq-to-entities

我有一个包含三列的表,我想使用自联接并检索具有别名的列。

表: Material (ID、名称、MaterialParentID)

public List<Material> GetMaterialList()
{
    List<Material> materilaList = new List<Material>();
    var query = (from c1 in db.Materials
                 join c2 in db.Materials on c1.ID equals c2.MaterialParentID
                 select c2);        

    return query.ToList();
}

我想将以下内容添加到现有查询并返回列表

select new { c2.ID, c2.MaterialParentID, c2.Name, ParentName = c1.Name })

最佳答案

只需使用实际的具体类型而不是匿名类型:

select new Material { 
    ID = c2.ID, 
    MaterialParentID = c2.MaterialParentID, 
    Name = c2.Name,
    ParentName = c1.Name 
}

关于c# - 我们可以在 C# 中使用 Linq toentity 将匿名类型转换为 List <T> 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17694241/

相关文章:

linq - 如何转换此 linq 表达式?

c# - 使用 Linq 按 List<ListItem> 进行过滤

c# - 如何在 WPF 屏幕空间中使用 4 个点来扭曲图像?

c# - 使用 LINQ 在列表中智能迭代

c# - 规范化 Canvas wpf 中的真实世界数据

c# - 设置精度c#

c# - Linq:如何获取二级节点的值

c# - 使用 Entity Framework 从 SQL 数据库中获取除 SQL 之外的所有内容

c# - 使用 Linq to Entities 的“Contains()”解决方法?

c# - 带有新属性的 LINQ 继承 "Down-Cast"