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

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

Popular Answer

The database and tables are created once you write a single line of code in the model. I assume your application includes the Entity Framework library. Here is an illustration of how to create a database utilizing the "Code First Approach" before moving on to simple CRUD operations.

Create a model first. 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; }
   }

To merely construct a database, place the following code in the controller or any other.cs file.

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