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?
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();
}