DotnetSparrow
DotnetSparrow

Reputation: 27996

Entity Framework 4 error

I have created MVC3 application using Entity Framework Code First method. My model is very simple:

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

and context class is

public class EmployeeDB : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }

and controller looks like this:

EmployeeDB context = new EmployeeDB();

        public ActionResult Index()
        {
            return View(context.Employees);
        }      
    }

I have created EmployeesDb.mdf and Employee table.

but I get this error:

The model item passed into the dictionary is of type 'System.Data.Entity.DbSet`1[DFEmployees.Models.Employee]', but this dictionary requires a model item of type 'DFEmployees.Models.Employee'. 

[Updated]

@model DFEmployees.Models.Employee

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

Please suggest solution.

Upvotes: 1

Views: 1448

Answers (2)

Jonathan
Jonathan

Reputation: 12015

It's looks like your view are waiting for a single employee, and you are triying to fill the view with a DBSet of employees.

To solve it, you can set the @model of the view to an IEnumerable of employees, or send only one employee to the view, depending of what are you showing in the view.

EDIT: I think this problem is not related with the previous one. Check this link, I hope it helps you: LINK

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039478

Your controller action returns a list of employees so adapt your model respectively in the view:

@model IEnumerable<DFEmployees.Models.Employee>

Or if you wanted to use a single employee make sure you pass a single employee to the view:

public ActionResult Index()
{
    return View(context.Employees.FirstOrDefault());
}

and then you can have:

@model DFEmployees.Models.Employee

Upvotes: 0

Related Questions