EF5 db.Database.SqlQuery映射返回对象

本文关键字:返回 对象 映射 SqlQuery db Database EF5 | 更新日期: 2023-09-27 17:49:53

我有两个c#类

public class SearchResult
{
    public int? EntityId { get; set; }
    public string Name { get; set; }
    public Address RegisteredAddress { get; set; }
}

public class Address
{
    public int? AddressId { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Address3 { get; set; }
}

在dbContext调用中使用,通过EF5映射从数据库返回的对象

using (DbEntities db = new DbEntities())
{
    querySearchResult = db.Database.SqlQuery<SearchResult>(
        @"SELECT e.entity_id AS EntityId, e.entity_reg_name AS Name,
              a.address_1 AS [RegisteredAddress.Address1]
          FROM
              entity AS e
              LEFT JOIN address AS a ON e.entity_reg_addr_id = a.address_id",
        objectParameterList.ToArray()).ToList();
}

我遇到的问题是,我似乎不能得到地址对象映射,即使有地址数据返回。

EF5 db.Database.SqlQuery映射返回对象

SqlQuery不支持Complex Type

你应该做的是:

internal class TempResult
{
    public int? EntityId { get; set; }
    public string Name { get; set; }
    public int? AddressId { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Address3 { get; set; }
}
var tempResults = db.Database.SqlQuery<TempResult>(
    @"SELECT e.entity_id AS EntityId, e.entity_reg_name AS Name,
          a.address_1 AS [RegisteredAddress.Address1]
      FROM
          entity AS e
          LEFT JOIN address AS a ON e.entity_reg_addr_id = a.address_id",
    objectParameterList.ToArray()).ToList();
querySearchResult = tempResults.Select(t => new SearchResult
{
    EntityId = t.EntityId,
    [...]
    RegisteredAddress = new Address 
        {
            AddressId = t.AddressId,
            [...]
        }
}