Introduction
This article demonstrates how we can set up customer Entity framework in .Net applications (console application) with a step by step example.
Tools Used for development
- Visual Studio 2019
- SQL server
Step 1 - Create Application
- Create Blank solution CustomerEF
- Class library .NET Standard
- CustomerEF.Domain
- CustomerEF.Data
Step 2 - Adding Classes
Add class in CustomerEF.Domain class library
- public class Customer
- {
- public Customer()
- {
- Address = new List<Address>();
- }
- public int Id { get; set; }
- public string CustomerName { get; set; }
- public List<Address> Address { get; set; }
-
- }
-
- public class Address
- {
- public int Id { get; set; }
- public string Street { get; set; }
- public string PinCode { get; set; }
-
- }
Step 3 - Adding migration and DbContext
Install EntityFramework via nuget package manager to CustomerEF.Data Class library
Add CustomerContext.cs in CustomerEF.Data
- public class CustomerContext : DbContext
- {
- public DbSet<Customer> Customers { get; set; }
- public DbSet<Address> Addresses { get; set; }
- }
In Package Manager console run the below command, under CustomerEF.Data
enable-migrations
Add constructor with db connection string in CustomerContext.cs
- public class CustomerContext : DbContext
- {
- public CustomerContext() : base("Data Source=(local)\\SQLexpress;Initial Catalog=CustomerEFCORE;Integrated Security=True")
- {
- Database.SetInitializer(new MigrateDatabaseToLatestVersion<CustomerContext, Configuration>());
- }
- //...
- }
In Package Manager console run the below command, under CustomerEF.Data,
- add-migration initial-setup
- update-database
Step 4 - Create Console App
- Create console app and make it like a default project
- Add EntityFramework via Nuget package manager (We can implement Repository Design pattern to make the code better)
- class Program
- {
- static CustomerContext context = new CustomerContext();
-
- static void Main(string[] args)
- {
- GetCustomer("Before Add: ");
- AddCustomer();
- GetCustomer("After Add: ");
- Console.ReadKey();
- }
-
- private static void GetCustomer(string text)
- {
-
- var customers = context.Customers.ToList();
-
- Console.WriteLine($"{text}: Customer Count is {customers.Count}");
-
- foreach (var customer in customers)
- {
- Console.WriteLine(customer.CustomerName);
- }
- }
-
- private static void AddCustomer()
- {
-
- var customer = new Customer { CustomerName = "Swetha" };
- var address = new Address { Street = "Bangalore", PinCode = "560091" };
- context.Customers.Add(customer);
- customer.Address.Add(address);
- context.SaveChanges();
- }
-
- }
Summary
In this article, I discussed how we can set up Entity framework in console applications with a step by step example.