I am building a test application using MVC3, Razor, and Entity Framework 4.1 with a schema-first approach (as apposed to a code-first approach), in a repository pattern. I would like to avoid accessing data objects in my view, and access a model instead, but I am having a problem. As far as I can tell, the data objects are being returned from the data layer as ObjectSet, but my View needs IEnumerable, and I don’t know how to cast one to the other.
Here is some code, to help clarify.
Model …
namespace TestSolution.Models
{
public class ProjectModel
{
[HiddenInput]
public int Id { get; set; }
[Required]
[StringLength(255, ErrorMessage = "The name cannot be more than 255 characters long.")]
[Display(Name = "Name")]
public string Name { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
}
}
Repository …
public IQueryable<ProjectModel> GetProjects()
{
return Db.Project;
}
Entities …
public ObjectSet<Project> Project
{
get
{
if ((_Project == null))
{
_Project = base.CreateObjectSet<Project>("Project");
}
return _Project;
}
}
Controller …
public ActionResult Index()
{
IEnumerable<TestSolution.Models.ProjectModel> model = _projectRepository.GetProjects();
return View(model);
}
View …
@model IEnumerable<TestSolution.Models.ProjectModel>
Error I am getting when building …
Cannot implicitly convert type 'System.Data.Objects.ObjectSet<TestSolution.Project>' to 'System.Linq.IQueryable<TestSolution.Models.ProjectModel>'. An explicit conversion exists (are you missing a cast?)
Does this question make sense? I am just not sure where go from here … any advise you guys can give me would be awesome. 🙂
EDIT: I was able to solve this with Kyle’s suggestion by changing my Repository code to …
public IQueryable<ProjectModel> GetProjects()
{
return Db.Project.Select(i => new ProjectModel() { Id = i.Id, Name = i.Name, Description = i.Description });
}
The problem isn’t converting from
ObjectSet<T>toIEnumerable<T>(ObjectSet<T>implementsIEnumerable<T>).The problem is converting from
TestSolution.ProjecttoTestSolution.Models.ProjectModel. You will need to write some conversion code, maybe something similar to the below: