3

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

2 Answers 2

3

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; } } 
Sign up to request clarification or add additional context in comments.

1 Comment

I feel dumb for asking, now that it seems self-explanatory. +Answer to you because the "ApplicationNameDBContext" helped me understand.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.