Linq to Entities Only Supports Casting Edm Primitive or Enumeration Types with Ientity Interface

LINQ to Entities only supports casting EDM primitive or enumeration types with IEntity interface

I was able to resolve this by adding the class generic type constraint to the extension method. I'm not sure why it works, though.

public static T GetById<T>(this IQueryable<T> collection, Guid id)
where T : class, IEntity
{
//...
}

LINQ to Entities only supports casting EDM primitive or enumeration types. (interface)

Is it possible to cast Capacitor for IParentEquipment in this query?

There is no need to do casting for this code to work.

var query = (
from e in ((IAppContext)_ctx).Capacitor
where e.Name.Equals(name)
select e).Distinct();

equipments.AddRange(query);

LINQ to Entities only supports casting EDM primitive or enumeration types (unique new post)

EF does not support such casts, so no Expression.Convert should be used.

The actual problem is that Expression.Lambda(call_select, p) returns Expression<Func<T, IQueryable<R>>> which you are trying to cast to Expression<Func<T, IEnumerable<R>>>. But Expression as any C# class does not support variance, hence the cast expectedly fails.

The solution is to use Expression.Lambda method overloads which allow you to specify the desired result type. In your sample, it could be like this:

var selector = Expression.Lambda<Func<SystemEntitlement, IEnumerable<SystemAssociateModel>>>(
call_select, p);

Once you do that, the problem will be solved.

As a side note - when you build expressions dynamically, there is no need of applying AsQueryable on collection navigation properties - it's used to trick the C# compiler to allow using Expression<Func<...>> variable inside what you call literal expressions in methods that expect Func<...>. When you emit Expression.Call by hand, you could simply call the corresponding Enumerable method:

var call_select = Expression.Call(ExpressionHelpers.GetMethodInfo(
() => Enumerable.Select(default(IEnumerable<SystemAssociate>), default(Func<SystemAssociate, SystemAssociateModel>))),
memberPath, projector);

Here I'm guessing the expected arguments of your ExpressionHelpers.GetMethodInfo. I personally "call" generic methods like this:

var call_select = Expression.Call(
typeof(Enumerable), "Select", new[] { typeof(SystemAssociate), typeof(SystemAssociateModel) },
memberPath, projector);

Of course AsQueryable doesn't hurt in EF6, but is redundant and is not supported in EF Core.

Cast() exception: LINQ to Entities only supports casting EDM primitive or enumeration types

Since you're getting all of the entities, you could materialize the query first, then perform the cast.

This would perform the Cast in memory instead of trying to formulate it as part of the query translation. The error comes because LINQ to Entities doesn't support transforming the SQL to a non-entity class, even when it inherits from an entity class, because there is no mapping for the additional columns to the SELECT statement. By materializing the data, then performing the Cast in memory (LINQ to Objects), you avoid the translation error.

However, in your case, you have the inheritance backwards for this to work. For it to work, I'd suggest having the DB model implement IDataModel and avoid the cast entirely, see http://msdn.microsoft.com/en-us/library/vstudio/bb738696(v=vs.100).aspx and http://msdn.microsoft.com/en-us/library/wa80x488.aspx. In particular, your partial class can implement the interface (honestly don't remember if the designer allows you to add an interface definition since I only do code-first these days). Note that may remove the need for your view-specific model entirely.

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

The alternative, which I would probably do, is keep the view model completely separate (not have it inherit from the entity class) and use AutoMapper to map between them.

var criminalEvents = db1.CriminalEvents.ToList();
viewModel.CriminalEvents = Mapper.Map<CriminalEventViewModel>(criminalEvents);

LINQ to Entities only supports casting EDM primitive or enumeration types - How to fix without ToList() call

A bit tricky, but doable.

First we need a helper generic constrained function. Since from your definition looks like the GetQueryable function is part of a generic class, let put the helper function in a separate class

public static class StoreScopedEntity
{
public static Expression<Func<T, bool>> IdPredicate<T>(int id)
where T : IStoreScopedEntity
{
return e => e.Stores.Select(s => s.Id).Contains(id);
}
}

I assume StoreScopeId is of type int, but you can change it to actual type if it's different.

Now the only remaining is how to call that function. There are several ways of doing that, here I'll use pure reflection

public IQueryable<T> GetQueryable()
{
var results = _repository.Table;
if (typeof(IStoreScopedEntity).IsAssignableFrom(typeof(T)))
{
results = results.Where((Expression<Func<T, bool>>)
typeof(StoreScopedEntity)
.GetMethod("IdPredicate", BindingFlags.Public | BindingFlags.Static)
.MakeGenericMethod(typeof(T))
.Invoke(null, new object[] { EngineContext.Current.StoreScopeId }));
}
return results;
}

LINQ to Entities only supports casting EDM primitive or enumeration types error

EF does not recognize the implicit conversion from Nullable<T> to object, which the compiler generates for the .Equals() call.

Change that to the == operator and you should be fine, because the spec defines an equality operator between T and Nullable<T>.

Unable to cast the type 'x' to type 'y'. LINQ to Entities only supports casting EDM primitive or enumeration types

AFAIK this is not possible with EF in that way, as EF can't translate that to SQL. But maybe a small structural change would help:

return DbContext.Projects.Include(t => t.Tasks).Select(p => new ProjectDto
{
Id = p.Id,
Name = p.Name,
Tasks = p.Tasks.Select(t => new TaskDto()
{
Id = t.Id,
Name = t.Name,
ProjectId = t.ProjectId,
Task = t,
KeyId = t.KeyId
}).ToList()
});

and in the TaskDto:

public X Selector => (Task as Task1)?.Selector;
public X Task2Property => (Task as Task2)?.Task2Property;
public X SelectorPosition => (Task as Task3)?.SelectorPosition;

Where X is the appropriate type for each property (and => the short form for { get { return x; } } if you are still using an older version of C#).

LINQ to Entities only supports casting EDM primitive or enumeration types

Try to use:

public ActionResult listBidder(string sort, string sortdir, int? page)
{
int startPage = 0;
if (page.HasValue && page.Value > 0)
{
startPage = page.Value;
}
var sList = _istudentrepository.GetList(startPage, PageSize, sort, sortdir);
return View(sList);
}

public IEnumerable<Students> GetList(int intPage, int intRecords, string strSort, string sortdir)
{

var finalresult = new Students();
var bidList = (from userInfo in _entity.tbl_UserInf
join user in _entity.tbl_User on userInfo.UserId equals user.UserId
select new Students()
{
intID=user.UserId,
strFirstName = user.FirstName,
strEmail = userInfo.EmailId,
intPhone=userInfo.Phone
}).OrderByDescending(m => m.intID);
finalresult.TotalResult = bidList.Count();
// There are some sorting and ordering
finalresult.lstStudents = sList.Skip(intPage * intRecords).Take(intRecords).ToList();
return bidList.ToArray();

}



Related Topics



Leave a reply



Submit