Entity Framework – Console App

Assumptions:

  • you have local SQL Server installed
  • database does not exist
  • user has permissions to SQL server to create db

Create a new Console Application using Visual Studio 2013.  Add a nuget reference to Entity Framework (I used latest version 6.1.3)

Enter code:


using System.Data.Entity;

namespace EntityFwkConsoleApp
{
    class Program
    {
        const string _connectionString = "Server=.;Database=Testing123;Trusted_Connection=True;Workstation Id=eftest";

        static void Main(string[] args)
        {
            using (var db = new MyDbContext(_connectionString))
            {
                var widget = new Widget {Name = "widget 1"};

                db.Widgets.Add(widget);
                db.SaveChanges();
            }
        }
    }

    public class MyDbContext : DbContext
    {
        public MyDbContext(string connection) : base(connection)
        {
            
        }

        public DbSet<Widget> Widgets { get; set; }
    }

    public class Widget
    {
        public int Id { get; set; }

        public string  Name { get; set; }
    }

}

Run the console app & notice the db is created, with a table and one row