简体   繁体   中英

Can't add controller of model that inherits from other class

I'm using Entity Framework and MVC3, and my problem is that I can't scaffold Controllers if the Model inherits from another Class.

Example:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class User : Person
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public class Context : DbContext
{
    public DbSet<Person> PersonSet { get; set; }
}

When I try to Add the Controller User using template Controller with read/write actions and views, using Entity Framework I get this error:

'User' is not part of the specified 'Context' class, and the 'Context' class could not be modifed to add a 'DbSet' property to it. (For example, the 'Context' class might be in a compiled assembly.)

I could add public DbSet<User> UserSet { get; set; } public DbSet<User> UserSet { get; set; } public DbSet<User> UserSet { get; set; } to the Context but I don't think it is the right aproach.

At the moment your User is not persisted type because context doesn't know that type so you cannot use scaffolding of persisted entity types to create controller for User type. If you want to store User and its properties in database add this to your context:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>();
}

If you don't want to persist User to database you cannot use scaffolding for controller creation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM