문제

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; }
}
도움이 되었습니까?

해결책

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; }
    }

다른 팁

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; }

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top