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