[英]Handle multiple result from a stored procedure with SqlQuery
我有一个存储过程,它返回多组结果(两个表)。 我这样调用存储过程:
var result = context.Database.SqlQuery<RefererStatisticResult>(
"exec [dbo].[GetReferrer] @StartDate, @EndDate, @Source",
this.CreateInParam("@StartDate", SqlDbType.DateTime, startDate),
this.CreateInParam("@EndDate", SqlDbType.DateTime, endDate),
this.CreateInParam("@Source", SqlDbType.SmallInt, eventSourveVal)).ToArray();
我的 RefererStatisticResult 包含两个 List<> 属性,用于结果集,但调用后列表为空。 如何处理结果集? SqlQuery 可以吗?
DbContext
没有对实现多个结果集的本机支持。 但是,通过下拉到ObjectContext
并使用Translate
方法将结果从DbDataReader
复制到域模型中的实体中,这是相当直接的。
这是一些示例代码。 这假设您的ReferrerStatisticResult
只是名为Set1
和Set2
的两个列表的容器。 显然根据您的实际域模型进行调整。
// Create container ready for the resultsets
var result = new RefererStatisticResult();
using (var myContext = new MyContext())
{
// Create command from the context in order to execute
// the `GetReferrer` proc
var command = myContext.Database.Connection.CreateCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[GetReferrer]";
// add in command parameters
// (not shown)
try
{
myContext.Connection.Open();
var reader = command.ExecuteReader();
// Drop down to the wrapped `ObjectContext` to get access to
// the `Translate` method
var objectContext = ((IObjectContextAdapter)myContext).ObjectContext;
// Read Entity1 from the first resultset
result.Set1 = objectContext.Translate<Entity1>(reader, "Set1", MergeOptions.AppendOnly);
// Read Entity2 from the second resultset
reader.NextResult();
result.Set2 = objectContext.Translate<Entity2>(reader, "Set2", MergeOptions.AppendOnly);
}
finally
{
myContext.Database.Connection.Close();
}
}
我认为以下代码可以帮助您。
MultiResultDomain domainEntity = new MultiResultDomain();
var command = _DatabaseContext.Database.Connection.CreateCommand();
command.CommandText = "[dbo].[SPR_GETMultipleResultSP]";
command.CommandType = CommandType.StoredProcedure;
try
{
_DatabaseContext.Database.Connection.Open();
var reader = command.ExecuteReader();
List<customcustomer> _listOfCustomer =
((IObjectContextAdapter)_DatabaseContext).ObjectContext.Translate<customcustomer>
(reader).ToList();
reader.NextResult();
List<customproduct> _listOfProduct =
((IObjectContextAdapter)_DatabaseContext).ObjectContext.Translate<customproduct>
(reader).ToList();
foreach (var cust in _listOfCustomer)
{
Console.WriteLine("Name: Mr.{0} And Country: {1}", cust.FirstName,
cust.Country);
}
foreach (var product in _listOfProduct)
{
Console.WriteLine("ProductName: {0} And Package: {1}",
product.ProductName, product.Package);
}
domainEntity.Customer = _listOfCustomer;
domainEntity.Product = _listOfProduct;
return domainEntity;
参考: 点击这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.