How to connect to SQL Server using ASP.NET MVC web application?

asp.net-mvc c# entity-framework sql-server

Question

I want to connect to SQL Server from my ASP.NET MVC application in Visual Studio. I type the following connection string in the web.config file:

<connectionStrings>
   <add name="EmploymentDbContext" 
        connectionString="Data Source=ASD-PC\SQLEXPRESS;Initial Catalog=EmploymentsHistory;Integrated Security=SSPI ;" 
        providerName="System.Data.SqlClient"/>
</connectionStrings>

My server name is ASD-PC\SQLEXPRESS and I use Windows Authentication to connect to SQL Server.

When I run the ASP.NET MVC project the project runs with success but the database EmploymentsHistory isn't there. How to fix that?

1
0
7/4/2015 11:54:53 AM

Popular Answer

Code First Approach - You just need to write a code in model after that database and tables will be created. I hope, you have added Entity Framework library in your application. Below is the example of first creating database by using "Code First Approach" after that you can easily do CRUD operation.

First create a model. Ex.

public class Person
    {
        [Key]
        public int Id{get;set;}
        [Required]
        public string name { get; set; }
        [Required]
        public string surname { get; set; }
    }

public class personContext : DbContext
    {
        public personContext()
            : base("EmploymentDbContext")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());
        }
        public DbSet<Person> person { get; set; }
   }

Use below code in controller or in any .cs file to only create a database.

using (var ctx = new personContext())
            {
                ctx.Database.Create();
            }
1
7/4/2015 11:43:16 AM


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