First, use EF Code to add many entities to the same table.

ef-code-first entity-framework

Question

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 :)

1
5
5/3/2012 6:52:57 PM

Accepted Answer

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.

9
5/4/2012 8:29:10 AM

Popular Answer

Table Per Hierarchy TPH inheritance in entity framework with code first

https://www.youtube.com/watch?v=2i7jahkpeQ8&list=PL6n9fhu94yhUPBSX-E2aJCnCR3-_6zBZx&index=19



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow