Cast() exception: LINQ to Entities only supports casting EDM primitive or enumeration types c# casting entity-framework linq-to-entities

Accepted Answer

You might materialize the query first, then execute the cast, since you are receiving all of the entities.

Instead of attempting to formulate the Cast as part of the query translation, this would do the Cast in memory. Even though it descended from an entity class, LINQ to Entities does not permit changing the SQL to a non-entity class since there is no mapping for the additional fields to the non-entity class.SELECT statement. Initially materializing the data, followed by theCast You can prevent the translation mistake by working in memory (LINQ to Objects).

However, for this to apply to you, the inheritance is reversed. I would advise that the DB model implement it for it to operate.IDataModel See and, and completely avoid the cast. In particular, your partial class can implement the interface (though, to be really honest, I don't remember if the designer allows you to add an interface definition as I only use code-first these days). Note that this might completely eliminate the necessity for your view-specific model.

viewModel.CriminalEvents = db1.CriminalEvents.ToList();

The option is to keep the view model fully separate (and not have it inherit from the entity class), and then use AutoMapper to map between them. This is what I would probably do.

var criminalEvents = db1.CriminalEvents.ToList();
viewModel.CriminalEvents = Mapper.Map<CriminalEventViewModel>(criminalEvents);
12/31/2013 5:08:08 PM

Popular Answer

Enumerable.Cast<TResult> is making an effort to cast each component in the collection. The reason it fails in your circumstance is that you are attempting to cast instances of parent (which is not surprising).AIM.Police.DB.CriminalEvent ) class to child objects (InvestigationSimulator.Models.CriminalEvent ) class. Such casting is not possible in C#.

To correct this, you must first load objects from your database before manually converting (mapping) them to your Model class. The simplest code is as follows:

viewModel.CriminalEvents = db1.CriminalEvents.ToList().Select(ce => new InvestigationSimulator.Models.CriminalEvent() { Id = ce.Id, }).ToList();

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow