简体   繁体   中英

ASP.net MVC 4, Connection string

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?

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

我有同样的问题,如果您已经有App_Data文件夹,请将其删除,然后从Project-> Add ASP.Net folder-> App_Data中添加一个新文件夹

When you start a new MVC 4 project with the "Internet Application" it adds a default connection string that points to a sql express database. Are you sure that you don't have that connection string in your web.config still?

I found this article - http://blogs.msdn.com/b/sqlexpress/archive/2011/12/09/using-localdb-with-full-iis-part-1-user-profile.aspx which resolves the issue. However this applies if user is running the App through IIS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM