soft_94 soft_94 - 2 months ago 8
C# Question

How To convert Model object list To Data object list in c# implicity

Here is my code in my model:

public class Employee:
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}


and here is my code in my controller:

public class EmployeeController : ApiController
{
Data.MainDataClassDataContext db =new Data.MainDataClassDataContext();
public List<Data.Pezeshk> Get()
{
var q = from e in db.Pezeshks
select new Models.Employee
{
Id = e.p_ID,
FirstName = e.p_Name,
LastName = e.p_Family,
};
return q.ToList();
}
}


and my data class is linq to sql data class, but my problem is in the last line
q.ToList();
I got this error:


you can not implicitly convert Model To Data

Answer

Your method's signature is public List<Data.Pezeshk> Get() while the list you are constructing contains objects of type new Models.Employee.

I assume you want to change this: public List<Data.Pezeshk> Get() to this: public List<Models.Employee> Get()

And as a side note - Maybe you'd want to return IEnumerable<Employee> instead of converting it to a List