如何将原始查询字段映射到实体的类字段?

时间:2018-12-14 14:34:02

标签: c# entity-framework

我有一个查询:

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(查询) 获取ProductView的列表,其中ProductView是

class ProductView
{
    string Name;

    GroupView Group;
}

class GroupView
{
    int id;
    string Name;
}

1 个答案:

答案 0 :(得分:1)

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,
        }
}