Tejaswi Pandava
Tejaswi Pandava

Reputation: 506

Entity framework is not creating DB with the specified name instead it is creating a name of its own, why?

need help i am new to MVC and EF

So i am trying to create a DB using the code first Approach. I have specifed the following Connection String

<add connectionString="Data Source=(local);Initial Catalog=SalesERPDB;Integrated Security=True"
        name="SalesERPDAL" 
         providerName="System.Data.SqlClient"/>
  </connectionStrings>

and i was in a hope that EF will create a DB with the name SalesERPDB. Instead it has created a DB with the following name"MVC.DataAccessLayer.SalesERPDAL". where MVC.DataAccessLayer is the namespace where SalesERPDAL (a class) is declared which is inheriting DBcontext.

in short EF is naming the database with the fully qualified name of the class which is inhering DBcontext.

namespace MVC.DataAccessLayer
{
    public class SalesERPDAL : DbContext //i think it will help in interacting with DB
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder) //i think used to build a model
        {
            modelBuilder.Entity<Employee>().ToTable("TblEmployee");
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Employee> DALEmployees { get; set; } //Dbset will represent all the employees that can be queried from the database.

    }
}

i have 2 questions:

  1. Why is it taking the particular name instead of connection string's name?
  2. How can i modify my code such that i get access to name my server as i want?

Sorry if it is repeated question.

Upvotes: 0

Views: 69

Answers (1)

isidat
isidat

Reputation: 946

  1. Your constructor method is missing. ConnectionString name should be given as a parameter to base method, so that your application can know with what name to create a database. Otherwise it creates the database named as your DbContext class name (which is MVC.DataAccessLayer.SalesERPDAL).

  2. A constructor method can be added such as:

    public SalesERPDAL() : base("SalesERPDAL") { }

Upvotes: 2

Related Questions