Naman Goyal
Naman Goyal

Reputation: 375

Entity framework creating separate database corresponding to each class in model

I have start using of Entity framework in ASP.NET MVC4.

I have created 3 classes in my Model folder and created controllers for every model.

Now when I run the application, it has created separate databases corresponding to every class of model.

Is there any way that we can use only one database?

Upvotes: 4

Views: 402

Answers (1)

Matt
Matt

Reputation: 2851

Are you creating a separate context for each of the classes?

public class Employee 
{
    [Key] public int EmpId { get; set; } // < Can I make a suggestion here
                                         // and suggest you use Id rather than
                                         // EmpId?  It looks better referring to 
                                         // employee.Id rather than employee.EmpId
    [Required] public string Fullname { get; set; }
    ...
}

public class AnotherClass
{
    ...
}

And then listing all your models in the context:

public MyDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<AnotherClass> AnotherClasses { get; set; }
}

You may also want to specify the connection string name by using a constructor in your Context:

public MyDbContext() : base("ConnectionString") {  }

It's important that all your models go in the same context.

Using the context

var context = new MyDbContext();
var employees = context.employees.ToList(); // I prefer storing the data as an IList

This tells EF to query the database and store the data within the employees variable.

Upvotes: 1

Related Questions