«Где» в свойстве правого соединения, допускающем значение NULL, Linq C# лямбда-выражение EF Core - PullRequest
0 голосов
/ 07 мая 2020

У меня есть запрос на перечисление группы Entity под названием Transaction with children. При попытке применить where для фильтрации опоры в дочернем элементе возникает недопустимая операция Linq. (EF Core)

Вот код:

var query = DataContext.Transactions
                .Select(x => new Transaction
                {
                    Id = x.Id,
                    TotalAmount = x.TotalAmount,
                    CreatedAt = x.CreatedAt,
                    TransactionState = x.TransactionState == null ? null :
                    new TransactionState
                    {
                        Id = x.TransactionState.Id,
                        Name = x.TransactionState.Name
                    },
                    Beneficiary = x.Beneficiary == null ? null :
                    new Beneficiary
                    {
                        Id = x.Beneficiary.Id,
                        DocumentNumber = x.Beneficiary.DocumentNumber
                    }
                })
                .AsNoTracking()
                .AsQueryable();

            if (!filter.IsNullEmtpyOrWhiteSpace()) // Own Property
            {
                // This is the line where apply where in prop
                query = query.Where(x => x.Beneficiary != null && x.Beneficiary.DocumentNumber.Contains(filter));
            }

            var count = query.Count();

            if (take > 0) query = query.Skip(skip).Take(take);

            return new ListAndCountDto<Transaction>
            {
                Data = query.ToList(),
                Count = count
            };

Это исключение ошибки:

"The LINQ expression 'DbSet<Transaction>\n    
.LeftJoin(\n outer: DbSet<Beneficiary>, \n        
inner: t => EF.Property<Nullable<int>>(t, 
\"BeneficiaryId\"), \n outerKeySelector: b => EF.Property<Nullable<int>>(b, \"Id\"), \n 
innerKeySelector: (o, i) => new TransparentIdentifier<Transaction, Beneficiary>(\n 
Outer = o, \n Inner = i\n ))\n .Where(t => EF.Property<Nullable<int>>(t.Inner, \"Id\") == null ? 
null : new Beneficiary{ \n Id = t.Inner.Id, \n DocumentNumber = t.Inner.DocumentNumber \n    }\n  
!= null && EF.Property<Nullable<int>>(t.Inner, \"Id\") == null ? null : new Beneficiary{ \n       
Id = t.Inner.Id, \n        DocumentNumber = t.Inner.DocumentNumber \n    }\n    
.DocumentNumber.Contains(__filter_0))' could not be translated. Either rewrite the query in a 
form that can be translated, or switch to client evaluation explicitly by inserting a call to 
either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See 
https://go.microsoft.com/fwlink/?linkid=2101038 for more information."

1 Ответ

0 голосов
/ 07 мая 2020

Обратите внимание на исключение ошибки, вы будете знать, что это вызвано тем, что ваш linq не может быть переведен. Поскольку вы используете Queryable, который вызывает оценку базы данных. Итак, что вам нужно сделать, это переписать запрос или использовать AsEnumerable () в качестве оценки клиента :

var query = DataContext.Transactions.AsEnumerable()
            .Select()...

ссылка : https://docs.microsoft.com/en-us/ef/core/querying/client-eval

...