簡體   English   中英

有沒有辦法將實體框架中的 where 子句設置為參數?

[英]Is there a way to set a where clause in Entity Framework to a parameter?

我有這個 EF qQuery

[HttpGet]
public IActionResult GetCISCustomers(string Option, string Input)
{
    using (var db = new cismodel.eedcbuildingdbContext())
    {
        var result = from a in db.ConsolidatedCustomerDatabase
                     where (a.AccountNo == Input)
                     select new
                            {
                                AccountNo = a.AccountNo
                            };

        string json = Newtonsoft.Json.JsonConvert.SerializeObject(result, Newtonsoft.Json.Formatting.Indented);

        return Ok(json);
    }
}

是否可以將a.AccountNo設為 (Option) 參數,因為我希望用戶能夠傳入不同的選項,例如(AccountNo、MeterNo、Name)和不同的輸入。

在此處輸入圖片說明

您可以將基本查詢編寫為 IQueryable 並根據您的條件進行過濾:

 IQuerable<EntityName> query= db.ConsolidatedCustomerDatabase;
 if(option == "A")
 {
      query = query.Where(x=>x.A == Input);
 }
 else if (option == "B")
 {
      query = query.Where(x=>x.B == Input);
 }

完成添加過濾后,您可以具體化查詢:

 var result = query.Select(x=> new {AccountNo = x.AccountNo}).ToList();

如果您知道Option的可能值,那么您可以構建如下所示的條件邏輯。

    var result = from a in db.ConsolidatedCustomerDatabase
                 where (Option == "AccountNo" && a.AccountNo == Input) 
                        || (Option == "MeterNo" && a.MeterNo == Input)
                 select new
                 {
                     AccountNo = a.AccountNo
                 };

您可以將表達式作為方法參數傳遞,例如

AccountNoType GetAccountNoForSelector(Expression<Func<Customer, bool>> selector)
{
    return db.ConsolidatedCustomerDatabase
        .Where(selector)
        .Select(c => c.AccountNo)
        .FirstOrDefault();
}

然后稱之為

var myAccount = GetAccountNoForSelector(c => c.MeterNo == 100);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM