Linq To Entity Error while checking the record if exist in database
I am getting an error when trying to use linqsql query:
LINQ to Entities does not recognize the method 'System.String get_Item(System.String)' method, and this method cannot be translated into a store expression.
Code:
 [HttpPost]
    public ActionResult CreateGiftVoucher(FormCollection collection)
    {
        IVoucherRepository voucherResp = new VoucherRepository();
        IQueryable<Voucher> getVoucher = voucherResp.GetAllVouchers();
        //if (getVoucher.Where(x => x.Code == collection["Code"]).Count() > 0) {
        if (getVoucher.Any(r => 开发者_运维问答r.Code == collection["Code"]))
        {
            ModelState.AddModelError("Code", "Code Already Exists");
        } return View(); }
Voucher Repository
 public IQueryable<Voucher> GetAllVouchers()
    {
        return entity.Vouchers;
    }
Your Linq query is translated to SQL, then executed on the database. But there is no SQL equivalent for collection["Code"], so the query can't be translated to SQL, hence the error. In that case the fix is easy: just put the result of collection["Code"] in a local variable outside the query.
    string code = collection["Code"];
    if (getVoucher.Any(r => r.Code == code))
    {
        ModelState.AddModelError("Code", "Code Already Exists");
    }
LINQ to entities cannot evaluate the expression collection["Code"]. Try evaluating that expression before the query:
string code = collection["Code"];
if (getVoucher.Any(r => r.Code == code))
{
    ...
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论