ASP.net MVC 4, Connection string

asp.net-mvc entity-framework

Question

I am learning MVC4 from http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/accessing-your-models-data-from-a-controller (edit: Fixed URL)

Everything is working perfectly but my database isn't getting updated but when I run the project the records are coming from somewhere and I couldn't find that database in my MSSQL.

My connection string in web.config is

<connectionStrings>
    <add name="PurchaseInfosDbContext" 
         connectionString="server=lakpa-pc;Integrated Security=SSPI; User ID=sa; Password=xxxxx; database=MessInfo" providerName="System.Data.SqlClient" />
</connectionStrings>

but in the Visual studio when I debug I get the connection string as

"Data Source=.\\SQLEXPRESS;Initial Catalog=Mvc4Projects.Models.ItemsDetailsDbContext;Integrated Security=True;MultipleActiveResultSets=True"

Isn't it supposed to read the connection string from web.config. I haven't modified any connection string on any pages.

a. Is it necessary to include SDF file as shown in that tutorial? Can't I directly update it to mdf file?

1
2
4/5/2013 4:41:50 PM

Accepted Answer

My problem was that the name of the class that was inheriting DbContext was different so MVC was taking default connection to SQLExpress even though I didn't specify it.

Well I changed the Class Name similar to Connection String name and now its pointing to correction location.

May be it will be helpful to someone. Problem faced and resolved

a. The Class that inherits DbContext must be used as a name for connection string.

b. The SQL Query that Entity framework add has plural table name so use the attribute [Table("PurchaseInfo")] to make it singular.

c. When using POCO method you will encounter a key problem if you don't follow its naming convention like in my example its Key must be "PurchaseInfoID" but I used ItemId . So use the attribute [Key] to solve this problem.

public  class PurchaseInfoDbContext : DbContext
    {
        public DbSet<PurchaseInfo> ItemsDetails { get; set; }
    }

    [DisplayName("Items Details")]
    [Table("PurchaseInfo")]
    public class PurchaseInfo
    {
        [HiddenInput]
        [Key]
        public int ItemId { get; set; }
}
5
8/16/2012 4:59:02 AM

Popular Answer

I have the same problem, if you already have App_Data Folder delete it and then add a new one from Project-> Add ASP.Net folder -> App_Data



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow