【问题标题】:Entity Framework Code First Stored Procedures with Multiple Result Sets and custom entity具有多个结果集和自定义实体的实体框架代码优先存储过程
【发布时间】:2016-10-14 17:23:40
【问题描述】:

我的存储过程返回两组结果。 ProductSearchResult 和 ProductSizeResult 在我的例子中不是实体,因此我得到一个异常 The EntitySet name 'Database.ProductSearchResult' could not be found.

我不想在 dbcontext 中为我的每个过程结果创建实体,是否有任何解决方案可以将存储过程映射到自定义对象。

        try
        {
            DbContext.Database.Connection.Open();
            DbDataReader reader = cmd.ExecuteReader();
            result = ((IObjectContextAdapter)DbContext).ObjectContext.Translate<ProductSearchResult>(reader, "ProductSearchResult", MergeOption.AppendOnly).ToList();
            reader.NextResult();
            productSizeResults = ((IObjectContextAdapter)DbContext).ObjectContext.Translate<ProductSizeResult>(reader, "ProductSizeResult", MergeOption.AppendOnly).ToList();
        }
        catch (Exception ex)
        {
            log.Error(ex);
        }
        finally
        {
            DbContext.Database.Connection.Close();
        }

我的自定义实体,

public class ProductSearchResult
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int AvailableQuantity { get; set; }

    public int Price{ get; set; }
}

public class ProductSizeResult
{
    public int Id { get; set; }

    public string Size { get; set; }

    public int Count { get; set; }
}

我的存储过程,

ALTER PROC GetProductResult @PrimaryCategory nvarchar(100)
AS

select P.Id
,P.Name
,PI.AvailableQuantity
,PI.Price
from Products P
inner join ProductInventories PI on P.Id = PI.ProductId
--where clause

select CA.Name Size,count(1) Count 
from Products P
inner join ProductInventories PI on P.Id = PI.ProductId
inner join CustomAttributes CA on PI.CustomAttributeID = CA.Id
--where clause
group by CA.Name

【问题讨论】:

    标签: c# sql-server stored-procedures entity-framework-6


    【解决方案1】:

    根据MSDN

    Translate 方法使您能够对数据源执行标准 ADO.NET 查询并将返回的数据行转换为 entity 对象。

    (我的重点)

    这意味着ProductSearchResultProductSizeResult 类型必须是映射类型(实体类型)。 MergeOption 参数已经或多或少地揭示了这一事实。那是关于如何将对象添加到更改跟踪器,这对于非实体类型没有意义。

    【讨论】:

      猜你喜欢
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多