Customer app with entity framework in .net framework 4.7.2
Step by step tutorials creating Entity framework 6
For feedback can drop mail to my email address amit.naik8103@gmail.com or you can create issue
- EF Core is an ORM (Object Relation Mapper)
- Microsoft's official data access technology for .NET development
- Developer productivity
- Coding consistency
- Create Blank solution EFCoreCustomer
- Class library .NET Standard
- EFCoreCustomer.Domain
- EFCoreCustomer.Data
- Install EntityFrameworko EFCoreCustomer.Data Class library
and Add class in EFCoreCustomer.Domain
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; }
}
Add CustomerContext.cs in EFCoreCustomer.Data
public class CustomerContext : DbContext
{
public CustomerContext() : base("Data Source=(local)\\SQLexpress;Initial Catalog=CustomerEFCORE;Integrated Security=True")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<CustomerContext, Configuration>());
}
public DbSet<Customer> Customers { get; set; }
public DbSet<Address> Addresses { get; set; }
}
Use EF Core Power Tool Extension for VS 2019
- In Package Manager console run below command, under EFCoreCustomer.Data
- enable-migrations (this will create configuration)
- Add-Migration init
- Update-Database
Create console app and make it as default project
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)
{
// Get all data from Customer table
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()
{
// For inserting to Customer table
var customer = new Customer { CustomerName = "Swetha" };
var address = new Address { Street = "Bangalore", PinCode = "560091" };
context.Customers.Add(customer);
customer.Address.Add(address);
context.SaveChanges();
}
}
- Install DGML editor in VS 2019 setup file (available in individual components)
- Install EF Core Power Tools via Extension
- Make multi target to netcoreapp3.1,netstandard2.0
- Add Microsoft.EntityFrameworkCore.Design lib via nuget package manager
- Create *.dgml file by right click on EFCoreCustomer.Data > EF Core Power Tools > Add DbContext Model diagram