[英]Entity Framework and Report Querying
什么是使用Entity Framework和SqlQuery()查询数据库的首选/最佳方法,其中返回数据为SUM和GROUP BY,并带有来自联接表的各种数据? 我不明白如何使用现有的POCO来返回一个POCO,它将代表所查询的数据。
例如,我有一个委员会类:
public class Commission
{
public long CommissionId { get; set; }
public int OrderId { get; set; }
public int OfferId { get; set; }
public decimal TotalRevenue { get; set; }
public int Quantity { get; set; }
public int MerchantId { get; set; }
public decimal MerchantRevenue { get; set; }
public string MerchantRepresentativeId { get; set; }
public decimal MerchantRepCommissionPercent { get; set; }
public decimal MerchantRepCommissionAmount { get; set; }
public DateTime DateCreated { get; set; }
[NotMapped]
public Offer Offer { get; set; }
[NotMapped]
public Merchant Merchant { get; set; }
[NotMapped]
public ApplicationUser MerchantRep { get; set; }
public Commission()
{
this.DateCreated = DateTime.Now;
}
}
我有这样的GetOfferCommissionListForMerchant()
方法:
public static List<Commission> GetOfferCommissionListForMerchant(int merchantId, DateTime? dateFrom = null, DateTime? dateTo = null)
{
using (AppDbContext db = new AppDbContext())
{
if (merchantId > 0)
{
var comms = db.Commissions.SqlQuery("SELECT [OfferId],[MerchantId],[MerchantRepresentativeId],SUM([TotalRevenue]) AS TotalRevenue,SUM([Quantity]) AS Quantity,SUM([MerchantRevenue]) AS MerchantRevenue,SUM([MerchantRepCommissionAmount]) AS MerchantRepCommissionAmount FROM [Commissions] WHERE [DateCreated] BETWEEN @p0 AND @p1 GROUP BY [MerchantRepresentativeId], [OfferId],[MerchantId]", dateFrom, dateTo);
return new List<Commission>(); **//This line is here to get the project to compile**
}
else
{
return new List<Commission>();
}
}
}
尽管此方法仅返回佣金,但我想获取位于不同表中的商户名称(基于MerchantId)以及每个返回的佣金行的其他相关数据位。 我对如何完成这项任务一无所知。
我知道这并不能解释我正在使用的整个领域,但是我试图了解完成这样任务的正确方法。 我将有其他报告以不同的方式使用相似的数据。
我是否需要还原到ADO.NET DataTable和DataSet方法? 我希望我可以在这个新的POCO /实体框架世界中完成以前在旧ADO.NET世界中所做的一切。
你的意见? 谢谢!
您可以但不应该使用Commission来报告,Commission是一个Entity,是上下文已知并绑定到表的类型。
您应该声明一种特定类型或使用匿名类型(但在这种情况下,必须在函数中使用它)
class ReportType {
MerchantRepresentativeId,
TotalRevenu
}
/* ... */
using (AppDbContext db = new AppDbContext())
{
if (merchantId > 0)
{
var comms =
from com in db.Commissions
group com by com.MerchantRepresentativeId into comGroup
select new ReportType {
MerchantRepresentativeId = com.MerchantRepresentativeId,
TotalRevenu = comGroup.Sum(x => x.TotalRevenu)
}
return comms.ToList(); **//This line is here to get the project to compile**
}
else
{
return new List<ReportType>();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.