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
Declaration Suffix for Decimal Type
How to Catch a Specific SQLexception Error
C# Base64 String to Jpeg Image
Authorization Header Is Lost on Redirect
Cancelling a Pending Task Synchronously on the UI Thread
How to Deserialize JSON with Duplicate Property Names in the Same Object
How to Get Current Page Url in MVC 3
Good Aes Initialization Vector Practice
How to Determine for Which Platform an Executable Is Compiled
Why Do We Need the New Keyword and Why Is the Default Behavior to Hide and Not Override
How to Read Data from a Zip File Without Having to Unzip the Entire File
How Much Memory Does a C#/.Net Object Use
How to Get a List of All Routes in ASP.NET Core
Using Static Variables Instead of Application State in ASP.NET
How to Select Text from the Richtextbox and Then Color It
How to View Msil/Cil Generated by C# Compiler? Why Is It Called Assembly