2

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; }
    }
3
  • Try creating a new migration "stringName" and update-database from the Package Manager Console they must match when you run the app. ( The reason I say this is because of the Error: "Invalid object name 'dbo.Products' Commented Sep 4, 2013 at 17:59
  • How do I go about writing this command inside the Package manager? Commented Sep 5, 2013 at 8:29
  • add-migration "stringNameOfWhatEverYouWantToCallThis" |||| update-database ( user verbose to show what its doing ) Commented Sep 5, 2013 at 12:19

1 Answer 1

2

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! :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.