EF核心异常System.ArgumentException:参数类型与System.Linq.Expressions.Expression.Condition(Expression test,Expression ....)不匹配

时间:2019-09-08 09:04:26

标签: c# linq entity-framework-core

我正在使用Entityframework-core 2.1.4,想运行以下查询,并尝试根据某些条件从导航属性中获取值。

var openInvoiceData = _Context.Invoice
    .Where(i => i.InvoiceDate.Date == model.CurrentDate.Date)
    .Select(i => new Contracts.OpenInvoiceData() {
        CustomerId = i.BillToId != null && i.BillTo.CustomerBillTo.Where(x => x.CustomerType == Enum.EnumCustomerType.BillTo).FirstOrDefault() != null
           ? i.BillTo.CustomerBillTo.Where(x => x.CustomerType == Enum.EnumCustomerType.BillTo).FirstOrDefault().Customer.CustomerId 
           : i.Customer.CustomerId
    }).ToList();

执行其真实部分时,将返回以下异常。

System.ArgumentException: Argument types do not match
   at System.Linq.Expressions.Expression.Condition(Expression test, Expression ifTrue, Expression ifFalse, Type type)
   at System.Linq.Expressions.ConditionalExpression.Update(Expression test, Expression ifTrue, Expression ifFalse)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.SqlTranslatingExpressionVisitor.VisitConditional(ConditionalExpression expression)
   at System.Linq.Expressions.ConditionalExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Remotion.Linq.Parsing.ThrowingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.SqlTranslatingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.SqlTranslatingExpressionVisitor.VisitUnary(UnaryExpression expression)
   at System.Linq.Expressions.UnaryExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Remotion.Linq.Parsing.ThrowingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.SqlTranslatingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.RelationalProjectionExpressionVisitor.Visit(Expression expression)
   at System.Linq.Expressions.ExpressionVisitor.VisitMemberAssignment(MemberAssignment node)
   at System.Linq.Expressions.ExpressionVisitor.VisitMemberBinding(MemberBinding node)
   at System.Linq.Expressions.ExpressionVisitor.Visit[T](ReadOnlyCollection`1 nodes, Func`2 elementVisitor)
   at System.Linq.Expressions.ExpressionVisitor.VisitMemberInit(MemberInitExpression node)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.RelationalProjectionExpressionVisitor.VisitMemberInit(MemberInitExpression memberInitExpression)
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.RelationalProjectionExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.VisitSelectClause(SelectClause selectClause, QueryModel queryModel)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor.VisitSelectClause(SelectClause selectClause, QueryModel queryModel)
   at Remotion.Linq.Clauses.SelectClause.Accept(IQueryModelVisitor visitor, QueryModel queryModel)
   at Remotion.Linq.QueryModelVisitorBase.VisitQueryModel(QueryModel queryModel)
   at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.VisitQueryModel(QueryModel queryModel)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor.VisitQueryModel(QueryModel queryModel)
   at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.CreateQueryExecutor[TResult](QueryModel queryModel)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](QueryModel queryModel)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](Expression query, IQueryModelGenerator queryModelGenerator, IDatabase database, IDiagnosticsLogger`1 logger, Type contextType)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass13_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Remotion.Linq.QueryableBase`1.GetEnumerator()
   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at TintPro.Repository.InvoiceRepository.GetOpenInvoices(GetOpenInvoice model) in C:\\Devendra Work\\TintPro\\Source BitBucket\\TintProAPI\\Repository\\Repository\\InvoiceRepository.cs:line 163
   at TintPro.Services.InvoiceService.GetOpenInvoices(GetOpenInvoice model) in C:\\Devendra Work\\TintPro\\Source BitBucket\\TintProAPI\\Services\\Service\\InvoiceService.cs:line 486
   at TintProAPI.Controllers.InvoiceController.GetOpenInvoice(GetOpenInvoice model) in C:\\Devendra Work\\TintPro\\Source BitBucket\\TintProAPI\\TintProAPI\\Controllers\\InvoiceController.cs:line 159
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()

我注意到以下情况:

  1. 仅当我尝试从“客户”导航属性中获取价值时才会抛出异常,这是其真正的部分,即
? i.BillTo.CustomerBillTo.Where(x => x.CustomerType == Enum.EnumCustomerType.BillTo).FirstOrDefault().Customer.CustomerId 
  1. 如果我使用以下语句代替它,那么它就起作用了
? i.BillTo.CustomerBillTo.Where(x => x.CustomerType == Enum.EnumCustomerType.BillTo).FirstOrDefault().CustomerId 

我无法找到导致此问题的原因,请帮忙。

2 个答案:

答案 0 :(得分:0)

似乎导航属性未加载。您将必须使用Include()方法进行加载。尝试下面的代码执行此操作

var openInvoiceData = _Context.Invoice
          .Where(i =>
          i.InvoiceDate.Date == model.CurrentDate.Date)
          .Select(i => new Contracts.OpenInvoiceData()
          {
              CustomerId = i.BillToId != null && i.BillTo.CustomerBillTo.Include(d=>d.Customer).Where(x => x.CustomerType == Enum.EnumCustomerType.BillTo).FirstOrDefault() != null
       ? i.BillTo.CustomerBillTo.Include(d=>d.Customer).Where(x => x.CustomerType == Enum.EnumCustomerType.BillTo).FirstOrDefault().Customer.CustomerId 
       : i.Customer.CustomerId
          }).ToList();

答案 1 :(得分:0)

我认为问题是在CustomerBillTo实体中未正确设置外键。只需仔细检查一下您是否已正确完成以下操作即可。

public class CustomerBillTo 
{
    [Required]
    [ForeignKey("Customer")]
    public string CustomerId { get; set; }

    public virtual Customer Customer { get; set; }
}

此外,由于您以.FirstOrDefault().Customer.CustomerId的身份访问。您必须将Customer与CustomerBillTo实体一起使用。因此,使其为必填项。否则,您将不得不处理空引用异常。