Override EF 5 database mapping

public class UserRepo
{
    private UserContext _context;
    public UserRepo(UserContext context)
    {
        _context = context;
    }
 
    public User Save(User user)
    {
        if (user.Id <= 0)
        {
            _context.Users.Add(user);
        }
        else
        {
            _context.Users.Attach(user);
        }
        return user;
    }
}
 
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}
 
public class UserMapping : EntityTypeConfiguration<User>
{
    public UserMapping()
    {
        HasKey(p => p.Id);
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).HasColumnName("Id");
        Property(p => p.Name).HasMaxLength(100);
 
        ToTable("User");
    }
}
 
public class UserContext : DbContext
{
    public DbSet<User> Users { get; set; }
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new UserMapping());
    }
 
    public UserRepo UserRepo
    {
        get
        {
            return new UserRepo(this);
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s