Martín
Martín

Reputation: 3125

MVC4 Entity Framework - Cannot implicitly convert

I created a Database using Entity Framework 5 from model. This model have a table called 'Person', and another one called 'Administrator'. 'Administrator' inherits from 'Person'.

Using MVC4 when I create a new Controller for 'Administrator'. When I create controller & views automatically this is the error:

Error 2 - Cannot implicitly convert type 'Model.Person' in 'Model.Administrator'. An explicit conversion exists (are you missing a cast?).

ERROR CODE (BETWEEN ASTERISKS):

public ActionResult Details(int id = 0)
    {
        **Administrator admin = db.Person.Single(u => u.Id == id);**
        if (admin == null)
        {
            return HttpNotFound();
        }
        return View(admin);
    }

Upvotes: 2

Views: 2333

Answers (3)

user1914530
user1914530

Reputation:

Administrator a = db.Person.OfType<Administrator>().Single(u => u.Id == id);

Use the OfType<>() filter method that only returns objects that can be cast to that type. Or alternatively explicitly cast the object.

Administrator a = db.Person.Single(u => u.Id == id) as Administrator;

Both of these solutions will work.

Upvotes: 5

Paul Berglund
Paul Berglund

Reputation: 91

Even in MVC 5.1 the scaffold generation doesn't know how to handle inherited types. You have to use the OfType<>() method to filter by object type like bmused stated.

Also - you need to use the SingleOrDefault() extension method to be able to get a null returned if there are no records. If you just use Single() and there are no records an exception will be thrown.

Upvotes: 1

user1513603
user1513603

Reputation: 11

'Administrator' inherits from 'Person'"

this mean an 'Administrator' is a 'Person' but a 'Person' may not be an 'Administrator'

you can have

Person p = new Administrator();

but

Administrator a = new Person();

is not correct and you need to make a cast.

Upvotes: 0

Related Questions