Get Max value for selected column of each row in Linq

 

https://forums.asp.net/t/2071927.aspx?Get+Max+value+for+selected+column+of+each+row+in+Linq

https://stackoverflow.com/questions/6864311/the-cast-to-value-type-int32-failed-because-the-materialized-value-is-null

https://forums.asp.net/t/1637613.aspx?LINQ+for+inserting+max+value+1

 

 

Advertisements

The entity or complex type cannot be constructed in a LINQ to Entities query

You cannot (and should not be able to) project onto a mapped entity. You can, however, project onto an annonymous type or onto a DTO:

public class ProductDTO
{
    public string Name { get; set; }
    // Other field you may need from the Product entity
}

And your method will return a List of DTO’s.

public List<ProductDTO> GetProducts(int categoryID)
{
    return (from p in db.Products
            where p.CategoryID == categoryID
            select new ProductDTO { Name = p.Name }).ToList();
}

 

Source: https://stackoverflow.com/questions/5325797/the-entity-cannot-be-constructed-in-a-linq-to-entities-query

Another Solution

http://www.c-sharpcorner.com/blogs/error-the-entity-or-complex-type-cannot-be-constructed-in-a-linq-to-entities-query1

 

LINQ inner query example

//var innerQuery = from depts in this.DbContext.Departments where depts.DeptName == “IT” select depts.DeptId;
            var innerQuery = from depts in this.DbContext.Departments where depts.DeptName == “HR” select depts.DeptId;
            //SELECT* FROM DEPARTMENTS WHERE DEPTID = 1;
            var result = from emp in this.DbContext.Employees where innerQuery.Contains(emp.DeptId) select emp;
            //SELECT * FROM EMPLOYEES WHERE DEPTID IN (1)
            //return employees;
            return result.ToList();