Question

I have an MVC3 project I created using the Code First paradigm and it works great. I created a model inheriting from DBContext, added the connection string, and I can write to the table and all that.

I can't seem to figure out how to add another table to the database using Code First, though. Adding another connection string that points to the same database doesn't work. Simply adding another class, creating a DBContext for it, and then adding and saving something to the new context doesn't work.

How do I add a new table to the database automatically using just code? My current web.config looks like this:

<add name="PersonDBContext"
     connectionString="Data Source=|DataDirectory|PersonData.sdf"
     providerName="System.Data.SqlServerCe.4.0"/>

My working model looks like this:

public class Person
{
    public int ID { get; set; }
    public string name { get; set; }
    public string country { get; set; }
    public string gender { get; set; }
}

public class PersonDBContext : DbContext
{
    public DbSet<Person> People { get; set; }
}

And finally what I want to create:

public class Dog
{
    public int ID { get; set; }
    public string name { get; set; }
    public string breed { get; set; }
}

public class DogDBContext : DbContext
{
    public DbSet<Dog> Dogs { get; set; }
}
Was it helpful?

Solution

Why wouldn't you create single context for both classes?

public class Person

    {
        public int ID { get; set; }
        public string name { get; set; }
        public string country { get; set; }
        public string gender { get; set; }
    }
    public class Dog
    {
        public int ID { get; set; }
        public string name { get; set; }
        public string breed { get; set; }
    }

    public class ApplicationNameDBContext : DbContext
    {
        public DbSet<Person> People { get; set; }
        public DbSet<Dog> Dogs { get; set; }
    }

OTHER TIPS

Just use:

public class Person
{
    public int ID { get; set; }
    public string name { get; set; }
    public string country { get; set; }
    public string gender { get; set; }
}

public class Dog
{
    public int ID { get; set; }
    public string name { get; set; }
    public string breed { get; set; }
}

public class PersonDBContext : DbContext
{
    public DbSet<Person> People { get; set; }
    public DbSet<Dog> Dogs { get; set; }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top