Skip to main content

Posts

Showing posts with the label EF Code First

LINQ: Grouping Data in LINQ using Group By

In this post I’ll explain how one can group data using LINQ GroupBy. GroupBy can be applied on different data types like Generic List, XML, DataTable etc. Syntax of Group By: var result= from c in <collection>     group c by c.<property> into g     select new     {         Key=g.Key,         Value=g     }; LINQ Grouping return partitioned sets of data from a collection based on a given key value, i.e. group employees by designation as: var query = from c in employees         group c by c.Designation; //or same statement can be written in Lambda expression as: var query = employees.GroupBy(c => c.Designation); GroupBy Result: Let’s understand result returned by LINQ grouping operation. The return collection fro...

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

While querying LINQ to Entities with check of Date, one may face the error like 'Date' is not supported in LINQ to Entities…… For example consider following LINQ statement, in which we are trying to get all employees created before today’s date: context.Employees.Where(c => c.CreatedOn >= DateTime .Now.Date ); If you compile this statement, it compiles successfully, however you'll get the error (mentioned below) when this query get executed. “The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported" Reason: Entity Framework doesn't allow the use of the Date member of DateTime inside an LINQ query. And because of the use of .Date member it throws the exception as when query get executed DateTime.Date cannot be converted to SQL statement. Solution: As I mentioned above LINQ to Entities queries are translated to SQ...

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

While using EF 4.1 code-first to insert data into a SQL Server database. If there is a validation error, EF throws a   DbEntityValidationException whose   EntityValidationsErrors   contains the details of the issue. For example you have set one field as required while creating model, but while saving data in that entity user have supplied Null value to that required field, EF throws a   DbEntityValidationException. There can be many other validation errors as well, and to see what exactly error EF is throwing, you can write you SaveChanges method in try..catch block as: try {     dbContext.SaveChanges(); } catch ( DbEntityValidationException e) {     foreach ( var error in e.EntityValidationErrors)     {          Console .WriteLine( "Entity of type \"{0}\" in state \"{1}\" has the following validation errors:" ,      ...