All Questions

Tagged with
Filter by
Sorted by
Tagged with
64 votes
11 answers
109k views

Get List<> element position in c# using LINQ

I have a List with numbers, and I'd like to find the position of the minimum (not value) using LINQ Example: var lst = new List<int>() { 3, 1, 0, 5 }; Now I am looking for a function returning ...
user avatar
61 votes
9 answers
70k views

You must add a reference to assembly mscorlib, version=4.0.0

I'm having some trouble migrating a web project from RC1 to RC2. When I switched, I'm getting a bunch of these errors throughout the project. The type 'Func<,>' is defined in an assembly that is ...
painiyff's user avatar
  • 2,639
34 votes
3 answers
120k views

The LINQ expression could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation

I have C# application (.NET Core 3.1) and I have written the following LINQ expression. public ActionResult<bool> GetItems(string title) { var items = _service.All.GetItems()....
Sheheryar Sajid's user avatar
25 votes
1 answer
24k views

Entity Framework Core: many-to-many relationship with same entity

I am trying to map many-to-many relationship with the same entity. The User entity has an IList<User> data field for Contacts, which stores users' contacts/friends information: public class ...
Lord Yggdrasill's user avatar
25 votes
2 answers
28k views

How to perform a group join in .NET Core 3.0 Entity Framework?

With the changes to .NET Core 3.0 I am getting ... NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?...
shelbypereira's user avatar
19 votes
2 answers
7k views

EF Core queries all columns in SQL when mapping to object in Select

While trying to organize some data access code using EF Core I noticed that the generated queries were worse than before, they now queried columns that were not needed. The basic query is just ...
Mad Scientist's user avatar
18 votes
3 answers
6k views

Nice examples of using .NET 4 dynamic keyword with Linq?

So I Just got a recommendation from Amazon for LINQ to Objects Using C# 4.0: Using and Extending LINQ to Objects and Parallel LINQ (PLINQ). It says that the book introduces using the dynamic keyword ...
Rei Miyasaka's user avatar
  • 7,027
16 votes
2 answers
19k views

Include / ThenInclude with where in EF Core [duplicate]

I need to use where in ThenInclude var templatesFields = await _context.Sections .Include(x => x.Subtitles) .ThenInclude(r => r.Fields.Where(t=>t.TemplatesFields.TemplateID==TemplateID)) ....
Rayan's user avatar
  • 183
15 votes
2 answers
1k views

Does "where" position in LINQ query matter when joining in-memory?

Situation: Say we are executing a LINQ query that joins two in-memory lists (so no DbSets or SQL-query generation involved) and this query also has a where clause. This where only filters on ...
Felix K.'s user avatar
  • 14.8k
13 votes
5 answers
15k views

Union with EF Core returns unable to translate set operation since both operands have different 'Include' operations

In a .NET Core 5 WebAPI project with EF Core 5, I'm trying to do a union on a LINQ query but I always get an error "unable to translate". The two entities I'm trying to concatenate are the ...
Giox's user avatar
  • 4,963
13 votes
2 answers
13k views

Use LinqKit PredicateBuilder for related model (EF Core)

I want to use LinqKit's PredicateBuilder and pass the predicate into .Any method for related model. So I want to build a predicate: var castCondition = PredicateBuilder.New<CastInfo>(true); ...
Igor's user avatar
  • 3,149
10 votes
4 answers
8k views

Linq WHERE EF.Functions.Like - Why direct properties work and reflection does not?

I try to perform a simple LIKE action on the database site, while having query building services based on generic types. I found out while debugging however, that performing EF.Functions.Like() with ...
Jan Pedryc's user avatar
9 votes
4 answers
14k views

ToAsyncEnumerable().Single() vs SingleAsync()

I'm constructing and executing my queries in a way that's independent of EF-Core, so I'm relying on IQueryable<T> to obtain the required level of abstraction. I'm replacing awaited SingleAsync()...
HappyNomad's user avatar
  • 4,508
9 votes
3 answers
4k views

How to group by week in Entity Framework Core?

In Entity Framework 6 I can use SqlFunctions.DatePart() method: var byWeek = data.GroupBy(x => SqlFunctions.DatePart("week", x.Date)); But these classes (DbFunctions and SqlFunctions are not ...
Nikolay Kostov's user avatar
8 votes
2 answers
2k views

Why is LastOrDefault(predicate) in LINQ faster than FirstOrDefault(predicate)

Introduction While testing performance differences with certain LinQ functions today, I noticed, that LastOrDefault(predicate) was almost always faster than FirstOrDefault(predicate), which got me a ...
Azzarrel's user avatar
  • 559
8 votes
1 answer
975 views

What does IPartition do in .NET Core?

I had a look at the .NET Core source in order to find out whether calls to IEnumerable.Last() (LINQ) are optimized when the collection implements IList which I suspected to be the case after some ...
user avatar
7 votes
1 answer
228 views

Why am I seeing a difference between.Cast<int>() and .Select(a => (int)a)?

I'm trying to work out the difference between the following: someListOfEnums.Cast<int>() and someListOfEnums.Select(a => (int)a)? I have found that the former causes an exception when ...
SBFrancies's user avatar
  • 4,132
7 votes
1 answer
6k views

LINQ expression is not being translated to SQL

I'm trying to achieve a compiled SQL query from LINQ which will check if query is substring of any of three columns in database (case insensitive). I'm using .NET Core 1.1 Query that I come up with ...
MaLiN2223's user avatar
  • 1,290
7 votes
1 answer
3k views

EF Core Include On Collection Class Property [duplicate]

I keep getting errors like : The property expression 'met => {from TrM x in met select [x].Tm}' is not valid. The expression should represent a property access: 't => t.MyProperty'. I have a ...
Lemex's user avatar
  • 3,780
6 votes
1 answer
27k views

How can I implement a LEFT OUTER JOIN in LINQ using lambda syntax on Entity Framework Core 2.0?

I am trying to implement a LEFT OUTER JOIN in Linq against an Entity Framework Core 2.0 DbContext. It's important that the query is translated to SQL, rather than evaluated locally. I've reviewed ...
Peter's user avatar
  • 5,835
6 votes
1 answer
12k views

Can Entity Framework (LINQ) select rows based on JSON where clause?

I have a column in a SQL database table of JSON data. Can I use Entity Framework and LINQ to query and filter based on a field/value in the SQL JSON column? I am using SQL 2016, VS 2017, EF Core 2.0, ...
paultechguy's user avatar
  • 2,418
6 votes
3 answers
17k views

Null reference exception being thrown in EF LINQ query if-clause

I couldn't find the exact words to explain what's happening, so if this is a duplicated question, I apologize. I tried to do a quite simple AND condition if-clause inside a LINQ Query, in order to ...
thiagoprzy's user avatar
6 votes
1 answer
789 views

Visual Studio assumes return value from FirstOrDefaultAsync() cannot be null

I have the following query. var railcarInfo = await (from rt in DbContext.RailcarTrips where rt.WaybillRailcar.RailcarNumber == clm.RailcarNumber && ...
Jonathan Wood's user avatar
6 votes
3 answers
1k views

How to translate TimeSpan calculations to SQL via LINQ

I'm having an entity with a TimeSpan property (Start) and an int (Duration in minutes) property. I want to perform a linq query that will fetch all the rows that apply to the following logic: Start &...
Dimitris's user avatar
5 votes
3 answers
15k views

Return async task using LINQ select

I want to implement function that return list of child items from database asynchronously. So I write a function: public async Task<IEnumerable<object>> GetFiles(int parentId) { ...
Roman Kolesnikov's user avatar
5 votes
1 answer
10k views

Entity Framework Core linq query returns InvalidCastException

I am currently creating a web api in .net CORE with Entity Framework. Whenever I try to select a single record by ID with linq, I get the following error: An exception of type 'System....
Max's user avatar
  • 2,424
5 votes
2 answers
1k views

C#/LINQ Taking Sum of Decimals show different results

I have a list of objects that I am attempting to take sum of after multiple 3 of the fields by each other. The problem is that the final result is NOT matching when I run the calculation by the ...
scorpion5211's user avatar
  • 1,050
5 votes
2 answers
362 views

Is the IEnumerable.OrderBy().First() optimisation in .Net Core 3.1 documented anywhere?

One of the .Net Core versions (I'm not sure which) introduced an optimisation such that if you write code like this: int smallest = new[]{ 7, 2, 4, 6, 0, 1, 6, 9, 8 }.OrderBy(i => i).First(); then ...
Matthew Watson's user avatar
5 votes
1 answer
824 views

How to map complex linq to object

Looking for a some help with Ef Core and Linq. Lets say I'm making big request to receive all support tickets with info about product, company, and so on. It's quite simple, just joining things: ...
Ice2burn's user avatar
  • 679
4 votes
2 answers
18k views

How to get all items of container in cosmos db with dotnet core

Hi I would like to get all items of a container in a database in cosmos DB. I can see that there are already a lot of methods available but I don't see any getAllItems or a lookalike. Is there an ...
Bendomin's user avatar
4 votes
2 answers
9k views

DotNet Core , No database provider has been configured for this DbContext

I want to select data from my table "Header" using a simple LINQ command but I faced error. My Action public HeaderModel GetHeaderInformation() { using(var context = new ...
Arash's user avatar
  • 1,768
4 votes
1 answer
1k views

Reflection .NET Core Create Lambda Expression

I'm trying to create a lambda expression (using Reflection) which looks like this IServiceProvider provider => provider.GetService<TDbContext>() Or, to be more specific, as GetService is an ...
Alex's user avatar
  • 431
4 votes
2 answers
2k views

Entity Framework LINQ complex query - combine multiple predicates

I'm trying to create a complex Linq query that goes like this: Get all organisations which have employees that match the given filter parameters. Example filter: Firstname: John Name: Smith My first ...
Arne's user avatar
  • 71
4 votes
1 answer
5k views

EF Core Decryption of SQL Column Level Encryption

My team and I are attempting to decrypt values from a db (Azure SQL) that has column level encryption turned on; with certs stored in key vault. Expected Result: var someLinqQuery = _contex.Users....
r_work_account's user avatar
4 votes
2 answers
86 views

How to order by 1 expression or 2 expressions based on a condition?

I am displaying businesses and people in a single result and would like to order them together. Pseudocode: if business name is not null order by business name else order by first name then last ...
David Spence's user avatar
  • 8,019
4 votes
1 answer
2k views

Client projection contains reference to constant expression of through instance method

I am getting this error on my LINQ Code Client projection contains reference to constant expression of through instance method This could potentially cause memory leak. Consider making the method ...
Hakuna's user avatar
  • 347
4 votes
1 answer
214 views

Unexpected behavior of LINQ Except()

I have encountered a strange bahavior of LINQ Except method which I don't understand. I can totally rewrite my code differently so that it works, that is not my problem. I just want to understand why ...
Maxim Zabolotskikh's user avatar
4 votes
2 answers
906 views

EF Core: LINQ Select "many-to-many-to-many" to "many-to-many"

I do have a table "Reference" and a table "Article" where a article references other articles. I do have simple references like: A -> B SQL: select ab.* from Article a inner join Reference ab on ab....
Stix's user avatar
  • 475
4 votes
2 answers
7k views

.NET Core 3.1 and Could not load file or assembly System.Data.Entity, Version=4.0.0.0

What Nuget package is System.Data.Entity in? I am converting a .NET Framework 4.5 app to .NET Core 3.1. In .NET Framework, it is using System.Linq.Dynamic, and the app is crashing when running this ...
Xaphann's user avatar
  • 3,417
4 votes
1 answer
4k views

Does .Net Core 2.1 Support LINQ and Lambda Expressions?

I have tried the following code on Visual Studio Code with OmniSharp extension has been installed. I installed .Net core 2.1.3. List<MyType> listName = dataTableName.AsEnumerable().Select(m =&...
ONLAEG's user avatar
  • 197
4 votes
1 answer
663 views

Accessing transparent identifier in select throws it is not referenced from scope

Accessing transparent identifier in select throwing exception. var result = (from t1 in table1 join t2 in table2 on t1.col1 equals t2.col1 into myTable1 from a in myTable1....
Chaitwo's user avatar
  • 249
4 votes
4 answers
1k views

Comparing sql with c# list in query?

I have a problem with comparing a value in my sql database with a list of object in my code. The object does not exist in DB Example of an object in the list: { public long CompareId public ...
LittleMygler's user avatar
4 votes
0 answers
465 views

EF Core define query using list instead of dbset in dbcontext

In EF Core using the modelBuilder a query can be defined for keyless entities like this: modelBuilder.Entity<UrlResource>() .ToInMemoryQuery(() => context.Blogs.Select(b => new ...
arkord's user avatar
  • 251
4 votes
0 answers
2k views

Entity Framework Core `HasConversion` property configuration not used when querying data with postgresql

I am using Entity Framework with Postgre through Npgsql, part of my configuration for the Cashout type which maps to the Cashouts table involves: public void Configure(EntityTypeBuilder<Cashout>...
Natalie Perret's user avatar
4 votes
0 answers
561 views

InvalidCastException in MySqlConnector while Math.Round inside LINQ-to-Entities

I have a question that I can not answer myself for now. The problem arose in the real scenario, but I simplified it for the question. I just wanted to make the rounding inside Select in LINQ. Perhaps ...
AlexDEV.pro's user avatar
4 votes
1 answer
3k views

ToListAsync throws 'Value cannot be null.' Exception

Having IQueryable var query = _db .ApplicationPaidServices .Include(it => it.Application) .Include(it => it.Application.User) .Where(it => Enum1.Value1 == it.Application....
tchelidze's user avatar
  • 8,190
3 votes
3 answers
9k views

How to create a dummy database for functional tests in .NET Core?

My app is built on .NET Core with Entity Framework 6. There are some complex C# LINQ queries that I am making against the db context. While I have XUnit unit tests that mock up the db and check the ...
Riz's user avatar
  • 6,546
3 votes
1 answer
187 views

Does Microsoft recommend method or query syntax? [closed]

Does Microsoft Net Core 3 recommend method syntax or query syntax for Linq Entity Framework queries? This is a debate in our workplace, we are curious. This is not Opinion based question, but fact, ...
AlexRodgers's user avatar
3 votes
3 answers
105 views

select from linq statement with await

This seems like it should be very simple, I have the following code var additionalInformation= response.AdditionalInformation.Select( async x => new AdditionalInformationItem { ...
jazza1000's user avatar
  • 4,169
3 votes
1 answer
1k views

.net core - combine a list of func with or to a single func

Hello i try to generate a single Func from a list combined by or. var funcs = new List<Func<User, bool>>() { (u) => u.Id.Equals(entityToFind.Id), (u) => u.UserName == ...
Flo's user avatar
  • 1,199

1
2 3 4 5
15