Search code examples
c#.netentity-frameworkasp.net-identitycode-first

Table not mapped using EF code first approach


I'd like to use EF code first approach. I added the database and I generate the tables . Then I added this class

  public class Invitation
    {

      
        [Key]
        public int Id { get; set; }

        [DefaultValue(false)]
        public bool State { get; set; }

        public string Mail { get; set; }

        public string Tel { get; set; }

        public string Name { get; set; }

        public string Qr_code { get; set; }
  
    }

I run these command then :

add-migrations second

update-database

the Up and Down methods of the second class migration are empty!! and no table is added to the database.

The context

 public class ApplicationContext: IdentityDbContext<ApplicationUser>
    {
         public ApplicationContext()
            :base("DefaultConnection")
        {
            Database.SetInitializer<ApplicationContext>(new CreateDatabaseIfNotExists<ApplicationContext>());
        }

        public static ApplicationContext Create()
        {
            return new ApplicationContext();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }

So I need to know

  1. What is the reason of this problem?
  2. How can I fix it?

Solution

  • Looks like you forgot to tell Entity Framework about the new table that you want added (DbSet<Invitation>)

    Once you add this, Entity Framework should add the table(s) you want added in the Migration script, respectively.

    In summation, you would need to add this line :

    public DbSet<Invitation> Invitations { get; set; }
    

    and/or

    public IDbSet<Invitation> Invitations { get; set; }
    

    and run another Migration Script.