im using Entity Framework designer first and I need to create custom Model Objects starting from the db objects. I don't want to use IEnumerable cause it will query too many fields.
The goal is to remove the inner select within this function:
using (var db = new dbEntities())
{
var departments= db.departments
.Include(p => p.employee)
.Where(...)
.Select(p => new CustomDepartmentModel()
{
ID = p.ID,
Employees = p.employee
.Select(q => new CustomEmployeeModel()
{
ID = q.ID,
Name= q.Name
}).ToList()
});
return departments.ToList();
}
by using this function:
public static IQueryable<CustomEmployeeModel> ToModel(this IQueryable<employee> Employee)
{
return Employee.Select(u => new CustomEmployeeModel()
{
ID = u.ID,
Name = u.Name
});
}
But I always get the error: "LINQ to Entities does not recognize the method ToModel".
I did try to use it in these ways without luck:
Employees = p.employee.AsQueryable().ToModel().ToList() //1
Employees = db.Entry(p).Collection(f => f.employee).Query().ToModel().ToList() //2
I think that I need to use something like this:
public static System.Linq.Expressions.Expression<Func<IQueryable<employee>, IQueryable<CustomEmployeeModel>>> ToModel()
{
return p => p.Select(u => new CustomEmployeeModel()
{
ID = u.ID,
Name = u.Name
});
}
but I really can't figure out how to use it.