I work with Entity Framework. There is a class

class Entity { public string Name { get; set; } public bool IsMain { get; set; } } 

I get data from the database using GroupBy:

 var grouppedEntitiesByName = context.GetEntities<Entity>().GroupBy(en => en.Name); 

The database has the following data:

 IsMain = true, Name = "entity" IsMain = false, Name = "entity" IsMain = true, Name = "Entity" 

After I do this:

  foreach (var entity in grouppedEntitiesByName) { var mainEntity = entity.Single(a => a.IsMain); } 

Here I get the error Sequence contains more than one matching element. The fact is that GroupBy gives three elements, it seems he does not distinguish between small and large letter. After I used ToList:

 var grouppedEntitiesByName = context.GetEntities<Entity>().ToList().GroupBy(en => en.Name); 

Everything is working. But why it does not work with IQueryable. Is there any solution to this problem?

  • That's right, the EF is designed so that by default all the lines are compared without regard to case, including Contains , GroupBy and others - Andrey NOP
  • Apparently, you need to change the collation of the column on the server side, as advised here: stackoverflow.com/a/3843382/6766879 - Andrew NOP
  • 2
    The problem is not in ef but in sql, which in principle compares case insensitive, although it may also depend on the database. - Grundy

1 answer 1

Try using FirstOrDefault instead of Single , like this:

 var mainEntity = entity.FirstOrDefault(a => a.IsMain); if(mainEntity != null) { ... } 

Single: selects a single item of the collection; if the collection contains more or less than one item, an exception is thrown.

  • This does not fit. As you can see on the database there is only one entity with IsMain == true. - DIlshod
  • @DIlshod db returns two values, case insensitive, so it fits - pasha goroshko
  • Such a decision destroys my logic. There are many entities in the database with the same name, only one of them is IsMain == true . For example, there is a give entity named 'MyEntity', but only one of them has IsMain == true - DIlshod