MVC核心存储库查询数据全部一次

时间:2018-05-22 08:14:52

标签: c# asp.net-mvc asp.net-core

我们有Customer事务表,其中包含多个带外键的查找表。我们希望看到3桌连在一起。

如何确保进行服务呼叫?我不想抓住所有不必要的客户交易,然后在内存中过滤。我想拨打一个服务电话来查找客户交易> 50个在一个SQL查询中。

存储库:

CustomerTransaction GetTransactionbyCustomerId(int customerid)
{
   var result = ct.CustomerTransaction.Where(x => x.CustomerTransactionId == customerid).ToList()
   return result;
}

服务电话:

void GetByCustomerTransactionGreaterthan50(int id)
{
   var newdata = CustomerTransaction.GetByCustomerTransactionId();
   nt.newdata.Where(x => x.PurchaseAmount > 50).ToList()
   return newdata;
}

模特:

public class CustomerTransaction
{
    public int CustomerTransactionId{ get; set; },
    public int ProductTypeId {get; set; }, //joins to ProductTypeTable
    public int StatusID {get; set; },  //joins to StatusTypeTable
    public string DateOfPurchase{ get; set; },
    public int PurchaseAmount { get; set; },
}

public class ProductType
{
    public int ProductTypeId{ get; set; }
    public string ProductName { get; set; },
    public string ProductDescription { get; set; },
}

public class StatusType
{
    public int StatusId{ get; set; }
    public string StatusName{ get; set; },
    public string Description{ get; set; },

}

2 个答案:

答案 0 :(得分:1)

您可以在Select之前进行ToList()投影,以确保EF生成的sql语句仅包含您正在投影的字段。

类似的东西:

var result = ct.CustomerTransaction.Where(x => x.CustomerTransactionId == customerid).Select(x=> new CustomerTransaction()).ToList()

并过滤您可以在where条件中包含您的过滤器:

ct.CustomerTransaction.Where(x => x.CustomerTransactionId == customerid && x.PurchaseAmount > 50)

或者让GetTransactionbyCustomerId像在服务调用中一样返回查询和过滤器

答案 1 :(得分:0)

选项1

您需要调整存储库,以便能够在服务层中添加您的查询:

<强>存储库:

IQueryable<CustomerTransaction> QueryTransactionbyCustomerId(int customerid)
{
   var result = ct.CustomerTransaction.Where(x => x.CustomerTransactionId == customerid);
   return result;
}

选项2

或者在数据访问层中创建另一种方法:

<强>存储库:

List<CustomerTransaction> GetTransactionByCustomerIdAndAmount(int customerid, int amount)
{
   var result = ct.CustomerTransaction.Where(x => x.CustomerTransactionId == customerid && x.PurchaseAmount > amount).ToList()
   return result;
}

根据您的架构,您应该选择其中一个选项。