[英]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.