Reputation: 869
Any idea what I could be doing wrong. I am trying to return object of Type AppRole by linking 2 tables. But I get error Explicit construction of entity type 'AppRole' in query is not allowed. How can I get object of type AppRole which meets the condition.
AppRole RoleName = (from role in dbContext.AppRoles
join user in dbContext.AppUsers on role.RoleID equals user.RoleID
where user.UserName.Contains(userNameDL)
select new AppRole
{
RoleID = role.RoleID,
RoleName = role.RoleName,
Description = role.Description,
Status = role.Status,
UpdateDate = role.UpdateDate
}).FirstOrDefault();
Upvotes: 1
Views: 58
Reputation: 7097
You cannot directly create that object as you just learned the hardway. When you call select new AppRole{}
you are explicitly creating a new one, which is unnecessary, since you already have a bunch of AppRole
objects in your query. You just want to pull one out of the collection.
Instead you can just do this:
AppRole RoleName = (from role in dbContext.AppRoles
join user in dbContext.AppUsers on role.RoleID equals user.RoleID
where user.UserName.Contains(userNameDL)
select role)
.FirstOrDefault();
select new
or .Select()
(with a lambda) is for making a projection, usually to a different datatype. Since you are running the query on already created AppRole
objects there is no need for this and instead we can just return the first that matches.
As to WHY you cannot do this it's because when you perform the linq-to-sql query (this is also the case in linq-to-entities) it will translate the code into SQL, however the object creation cannot be translated into SQL, so you will get an error message like you just experienced.
Upvotes: 2