LINQ and Entity Framework Errors

Possibly save 4 hours of your time: When working with LINQ and Entity Framework 6, you may encounter the following errors.

  1. Only parameterless constructors and initializers are supported in LINQ to Entities.
  2. The ‘Distinct’ operation cannot be applied to the collection ResultType of the specified argument. Parameter name: argument
    This happens on Union operation of two entities with different schemas
  3. An error occurred while preparing the command definition. See the inner exception for details.
    This happens on Union operation of Concat operation on two entities with different schemas
  4. System.InvalidOperationException : The specified cast from a materialized ‘System.Int32’ type to the ‘System.String’ type is not valid.
    This happens on Union or Concat operation on two entities with different schemas.

First one is obvious, you must have parameterless constructor when selecting new object transformation.

from i in dbcontext.TableName

select new EntityObjectName() { ID = i.ID }

Second and Third one is similar. When you select new object with properties that are in array form, you may get these errors. One idea would be to simply change this to IEnumerable or IList.

Fourth, this one took me awhile to figure out. It basically happens when the property being transformed came from two different tables and have different data types on the database backend. A simple fix is to check for null and turn into empty string on both the union/concat select. This seems to fix the issue.

from i in dbcontext.TableName

select new EntityObjectName() { Value = i.Value ?? “” }

UNION or CONCAT

from j in dbcontext.TableName2

select new EntityObjectName() { Value = j.Value2 ?? “” }

Programming Entity Framework: Code First: Creating and Configuring Data Models from Your Classes

Advertisements

One thought on “LINQ and Entity Framework Errors

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s