简体   繁体   中英

How to add a table and save data to an existing database

I used code first approach to create a database (that created "User.mdf" file that include a table called "users").

I added a new model:

public class Picture
{
    public int pictureId { get; set; }
    public int userId { get; set; }
    public string pictureUrl { get; set; }
}

public class PictureDBContext : DbContext
{
    public DbSet<Picture> Pictures { get; set; }
}

And tried to save data in a new table like this:

Picture curentImage = new Picture();
        curentImage.userId = int.Parse(Session["userId"].ToString());
        curentImage.pictureUrl = "/MyImages" + filename;

        if (ModelState.IsValid)
        {
            db.Pictures.Add(curentImage);
            db.SaveChanges();   
        }

I expected that it will create a new table for Pictures (as it worked in the user model)...

What is needed for making "EF magic" to know this model too and to create and add a Pictures table in the existing database? Will be happy to get an answer with the right way to save that data to a new table and few explantion if possible.

You are probably getting an error because the migration are turned off.

You could write your own migration to add the new table or you could use the automigrate feature of EF Code first.

If you want to write your own migration code you can read on this blog on own to do it: Code First Migrations

If you want to enable auto-migration. You can add this configuration class and it should do the trick.

internal sealed class PictureDBContextConfiguration : DbMigrationsConfiguration<PictureDBContext>
{
    public PictureDBContextConfiguration()
    {
        AutomaticMigrationsEnabled = true; // This will allow CodeFirst to create the missing tables/columns
        AutomaticMigrationDataLossAllowed = true;  //This will allow CodeFirst to Drop column or even drop tables
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM