首页 > 解决方案 > 如何将原始查询字段映射到实体的类字段?

问题描述

我有一个查询:

Select p.Name, p.ProductGroupID as GroupID, g.Name as GroupName
FROM Products as p
LEFT JOIN ProductGroups as g
    ON p.ProductGroupID = g.ProductGroupID

我可以使用 dbContext.Database.SqlQuery(query) 来获取 ProductView 的列表,其中 ProductView 是

class ProductView
{
    string Name;

    GroupView Group;
}

class GroupView
{
    int id;
    string Name;
}

标签: c#entity-framework

解决方案


SqlQuery 不支持复杂类型

你应该做的是:

internal class TempResult
{
    public string Name { get; set; }
    public int? id { get; set; }
    public int? AddressId { get; set; }
    public string groupName { get; set; }
}

var tempResults = db.Database.SqlQuery<TempResult>(
    @"Select p.Name, p.ProductGroupID as GroupID, g.Name as GroupName
FROM Products as p
LEFT JOIN ProductGroups as g
    ON p.ProductGroupID = g.ProductGroupID",
    objectParameterList.ToArray()).ToList();

querySearchResult = tempResults.Select(t => new SearchResult
{
    Name = t.Name,
    Group = new GroupView 
        {
            id = t.id,
            Name = t.groupName,
        }
}

推荐阅读