user2708073
user2708073

Reputation: 169

MVC 4 entity framework Not picking up database from SQL server

I am running with SQL server express 2008 R2 with a database and SQL authentication. I have added the database connnection to my server explorer and added the connection string to web.config file. When I debug the application it seems to be creating a default Database e.g. tutorial.MVC etc., instead of picking up the database I created prior to creating the app.

Also I am getting the compilation Error: {"Invalid object name 'dbo.Products'."} which should occur because the SQL is:

{SELECT 
[Extent1].[ProductID] AS [ProductID], 
[Extent1].[ProductName] AS [ProductName], 
[Extent1].[ProductPrice] AS [ProductPrice]
FROM [dbo].[Products] AS [Extent1]} 

There exists no table called products. This must have been generated by the entity framework database. Which I have deleted because the Products model class was originially Products where as the database table was called Product (human error) so it is failing to update the SQL. Essentially I just want the controller to map to the correct database. I suspect it isn't picking up the database from the connectionString. Although the connection string is being picked up by StoreContext when debugging. Seems not to be picking up the database. But can see why Web.config

<configuration>
  <connectionStrings>
    <add
      name="StoreContext"
      connectionString="Data Source=ADMIN-PC\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;User ID=Login;Password=***********"
      providerName="System.Data.SqlClient"
  />
  </connectionStrings>

global.asax

 public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            Database.SetInitializer<Tutorial.Models.StoreContext>(null);
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }

Product Controller

 public class ProductController : Controller
    { 

        StoreContext hello = new StoreContext();
        //
        // GET: /Product/
        public ActionResult Index()
        {

            var product = hello.Product.ToList();
            return View(product);

        }

    }

Product Model:

{
    [Table("Product")]
    public class Product
    { 

        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public double ProductPrice { get; set; }
    }
}

StoreContext:

public class StoreContext: DbContext
    {
        public DbSet<Product> Product { get; set; }
    }

Upvotes: 2

Views: 1618

Answers (1)

Lari
Lari

Reputation: 839

Have you set the correct DatabaseInitializer in your project?

IDatabaseInitializer contains 4 derived types that you can use: CreateDatabaseIfNotExists, DropCreateDatabaseAlways, DropCreateDatabaseIfModelChanges and MigrateDatabaseToLatestVersion

Choose the initializer that fit your needs and derive from it.

Next, on constructor of your context, set the initializer:

public Context() : base("ConnectionString")
{
    Database.SetInitializer(new MigrationsDatabaseInitializer());
}

MigrationsDatabaseInitializer is my derived class from MigrateDatabaseToLatestVersion.

Maybe your project is always recriating the database over and over.

You can disable pluralization with convention. Override OnModelCreation and remove pluralization convention:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    base.OnModelCreating(modelBuilder);
}

Hope it helps! :)

Upvotes: 2

Related Questions