Visual Studio Console App (.NET Framework) using Entity Framework and LocalDB

I often use Visual Studio and LocalDB in combination with Entity Framework 6+ for Prototyping or to make a quick sample. I also publish them sometimes to my Github Page

Sample Code for this post can be found here: https://github.com/itsChris/Sample-EF-RelationsApp

In the following steps we’ll:

  • Create a .NET Framework 4.5 Console App -> not .NET Core App!
  • Add Entity Framework Package to the project (Version 6.1.3)
  • Add a ConnectionString to a LocalDB Instance (in App.config)
  • Create a Model/Class Person with some properties

Create Project in Visual Studio 2019 Community Edition

Fire-up Visual Studio and select Create a new project

Search for Console App (.NET Framework) -> we’re not creating a .NET Core Project in this example! Then select the template

Give it a name, then create it

Start NuGet Package Manager Console

Use the following command to add the EntityFramework (Version 6.1.3) to the project

Install-Package EntityFramework -Version 6.1.3

Add a Class named DemoDataContext and make it inherit DbContext

Open App.Config and add a Connection String to use a LocalDB instance

	<connectionStrings>
		<add name="MyDemoDbContext" 
			 connectionString="Data Source=(localdb)\mssqllocaldb;Initial Catalog=MyDemoDb;Integrated Security=SSPI;" 
			 providerName="System.Data.SqlClient"/>
	</connectionStrings>

Create a Model (Add a Class) Person and add some properties like name and BirthDate etc. Also i created an Enum for the Gender.
I’ts important to add an ID/Key-Property/field. I’m a fan of GUIDs, so i deciced to add a PersonGuid of data type GUID as Key/Id using Data Annotations. Google for Entity Framework Data Annotations to get more info.

using System;
using System.ComponentModel.DataAnnotations;

namespace Sample_EF_RelationsApp
{
    public class Person
    {
        [Key]
        [Required]
        public Guid PersonGuid { get; set; }
        public string Firstname{ get; set; }
        public string Lastname { get; set; }
        public DateTime BirthDate { get; set; }
        public Gender PersonGender { get; set; }
    }
    public enum Gender
    {
        Male,
        Female,
        Both,
        Unknown
    }
}

Now make adjustments in the DemoDataContext Class.

  • Add a DbSet of Person
    public DbSet<Person> PersonList { get; set; }
  • Add a ctor/Constructor
        public DemoDataContext() : base("MyDemoDbContext")
        {
            Database.SetInitializer(new CreateDatabaseIfNotExists<DemoDataContext>());
        }

The SetInitializer method will create the Database using the method CreateDatabaseIfNotExists

Now let’s add a Person Object to the database, once we start our console App. Open Program.cs Class and add the following:

using System;

namespace Sample_EF_RelationsApp
{
    class Program
    {
    private static DemoDataContext db = new DemoDataContext();
        static void Main(string[] args)
        {
            Person p = new Person
            {
                BirthDate = DateTime.Now.AddYears(-45),
                Firstname = "Christian",
                Lastname = "Casutt",
                PersonGender = Gender.Male,
                PersonGuid = Guid.NewGuid()
            };
            db.PersonList.Add(p);
            db.SaveChanges();
            Console.WriteLine($"Person ({p.PersonGender}): {p.Lastname},{p.Firstname} " +
                $"born: {p.BirthDate} with GUID: {p.PersonGuid} added");
            Console.WriteLine("Press any key...");
            Console.ReadLine();
        }
    }
}

Now run the sample with F5 and wait for the console window..

Want to see whats happening ‘behind the Entity Framwork scenes’? Maybe this is of interest: https://blog.solvia.ch/2020/05/20/how-to-view-the-sql-generated-by-entity-framework/

Open SQL Server Management Studio (how? read https://blog.solvia.ch/2020/05/24/get-your-microsoft-sql-server-localdb-instance-up-and-running/)

e voila.

Feel free to comment/ask.