Ihor Korotenko
Ihor Korotenko

Reputation: 906

Mapping to existing table using Entity Framework

I face some difficulties when attemp to map my class to existing table using Entity Framework.

My class:

[Table("builder_User")]
public class MobileUser
{
    [Key]
    [Column("id")]
    public int Id { get; set; }
    [Column("beansCount")]
    public int BeansCount { get; set; }
    [Column("bonusSum")]
    public double BonusSum { get; set; }
    [Column("facebookUsername")]
    public string FacebookUserName { get; set; }
    [Column("firstName")]
    public string FirstName { get; set; }
    [Column("lastName")]
    public string LastName { get; set; }
    [Column("guid")]
    public string Guid { get; set; }
    [Column("job")]
    public string Job { get; set; }
    [Column("purchasedSum")]
    public double PurchasedSum { get; set; }
    [Column("facebookId")]
    public string FacebookId { get; set; }

}

My table in the database

enter image description here

And in DataContext class I have:

public DbSet<MobileUser> MobileUsers { get; set; }

But when I try to get users from the database, I get an exception

DbContext has changed since the database was created....

When I run add-migration command, it generates create table command.

So what is my mistake? Thanks

Upvotes: 5

Views: 5117

Answers (1)

Dealdiane
Dealdiane

Reputation: 4064

Set the initializer to null by calling Database.SetInitializer<TContext>(null) or Database.SetInitializer(new NullDatabaseInitializer<TContext>()

By setting the initializer to null, EF will no longer verify the database schema and will no longer create the database if the schema changes. You will have to create/update the database yourself after changing the schema.

Upvotes: 5

Related Questions