Admir Tuzović
Admir Tuzović

Reputation: 11177

EF Code First Multiple entities to same table

I am interested in how I can map two entities to same table, by using code first. Here's an example:

public class User
{
    [Key]
    public int UserId { get; set; }
    public string Name { get; set; }
    public byte Age { get; set; }
    public bool Active { get; set; }
    public DateTime Created { get; set; }
}

public class UserViewModel
{
    [Key]
    public int UserId { get; set; }
    public string Name { get; set; }
    public byte Age { get; set; }
}

Basically I'm fed up with building repositories. I want to map all possible models for configuration portal, user portal, other services in modelbuilder and just use DbContext for everything. I want to set User class as top of the hierarchy and a class that builds the database, while all other models should just be there for various applications.

I don't want to use automapper. I've also done fair amount of manual coding which just wasted my time, and every single modification requires me to go back to repository and recode - which annoys me.

I've tried to use this in modelbuilder, but it warns me that hierarchy is not valid:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().Map(p => { p.ToTable("Users"); });
        modelBuilder.Entity<UserViewModel>().Map(p => { p.ToTable("Users"); });
    }

Also keep in mind that I'm not trying to achieve "Table splitting". I don't want my table to be split in two entities, I want rather to have all columns nullable, except one with primary key, and allow different applications/web services/web portals to populate as much data as they've been granted access for.

Thanks for all the tips :)

Upvotes: 5

Views: 7934

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

You can't. One table = one entity (except advanced mappings like mentioned table splitting and TPH inheritance). View model is not and entity. It is just view on data / projection so handle it that way. You will always work with User and project user to view model you need:

var view = from u in context.Users
           select new UserViewModel
              {
                  UserId = u.UserId,
                  Name = u.Name,
                  Age = u.Age
              };

Make this as reusable method returning IQueryable<UserViewModel> and you can do whatever you want.

Upvotes: 10

Related Questions