Skip to content

Instantly share code, notes, and snippets.

@drasticactions
Created May 21, 2021 00:35
Show Gist options
  • Save drasticactions/cae288ce9c1cb9afcf9cdd769781579b to your computer and use it in GitHub Desktop.
Save drasticactions/cae288ce9c1cb9afcf9cdd769781579b to your computer and use it in GitHub Desktop.
EFCore AdventureWorks 2019
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace EFCorePKSample
{
class Program
{
static void Main(string[] args)
{
var db = new AdventureWorksContext();
var salesorderdetail = db.SalesOrderDetail.Include(n => n.Product).Include(n => n.SalesOrder).FirstOrDefault();
Console.WriteLine(salesorderdetail.Product);
Console.WriteLine(salesorderdetail.SalesOrder);
}
}
public class AdventureWorksContext : DbContext
{
public virtual DbSet<Address> Address { get; set; }
public virtual DbSet<Customer> Customer { get; set; }
public virtual DbSet<CustomerAddress> CustomerAddress { get; set; }
//public virtual DbSet<ErrorLog> ErrorLog { get; set; }
public virtual DbSet<Product> Product { get; set; }
public virtual DbSet<ProductCategory> ProductCategory { get; set; }
public virtual DbSet<ProductDescription> ProductDescription { get; set; }
public virtual DbSet<ProductModel> ProductModel { get; set; }
public virtual DbSet<ProductModelProductDescription> ProductModelProductDescription { get; set; }
public virtual DbSet<SalesOrderDetail> SalesOrderDetail { get; set; }
public virtual DbSet<SalesOrderHeader> SalesOrderHeader { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var serverKey = @"";
optionsBuilder.UseSqlServer(serverKey);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Address>(entity =>
{
entity.ToTable("Address", "Person");
entity.HasIndex(e => e.Rowguid)
.HasDatabaseName("AK_Address_rowguid")
.IsUnique();
entity.HasIndex(e => e.StateProvince);
entity.HasIndex(e => new { e.AddressLine1, e.AddressLine2, e.City, e.StateProvince, e.PostalCode, e.CountryRegion });
entity.Property(e => e.AddressId).HasColumnName("AddressID");
entity.Property(e => e.AddressLine1)
.IsRequired()
.HasMaxLength(60);
entity.Property(e => e.AddressLine2).HasMaxLength(60);
entity.Property(e => e.City)
.IsRequired()
.HasMaxLength(30);
entity.Property(e => e.CountryRegion)
.IsRequired()
.HasColumnType("Name")
.HasMaxLength(50);
entity.Property(e => e.ModifiedDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.PostalCode)
.IsRequired()
.HasMaxLength(15);
entity.Property(e => e.Rowguid)
.HasColumnName("rowguid")
.HasDefaultValueSql("(newid())");
entity.Property(e => e.StateProvince)
.IsRequired()
.HasColumnType("Name")
.HasMaxLength(50);
});
modelBuilder.Entity<Customer>(entity =>
{
entity.ToTable("Customer", "Person");
entity.Ignore(e => e.AddressCount);
entity.HasIndex(e => e.Rowguid)
.HasDatabaseName("AK_Customer_rowguid")
.IsUnique();
entity.Property(e => e.CustomerId).HasColumnName("CustomerID");
entity.Property(e => e.CompanyName).HasMaxLength(128);
#region Owned Types
var ownedCustName = entity.OwnsOne(x => x.CustomerName);
ownedCustName.Property(c => c.FirstName).HasColumnName("FirstName").IsRequired()
.HasColumnType("Name")
.HasMaxLength(50);
ownedCustName.Property(c => c.MiddleName).HasColumnName("MiddleName")
.HasColumnType("Name")
.HasMaxLength(50);
ownedCustName.Property(c => c.LastName).HasColumnName("LastName").IsRequired()
.HasColumnType("Name")
.HasMaxLength(50);
var ownedContact = ownedCustName.OwnsOne(x => x.Contact);
ownedContact.Property(c => c.EmailAddress).HasColumnName("EmailAddress").HasMaxLength(50);
ownedContact.Property(c => c.Phone).HasColumnName("Phone").HasColumnType("Phone")
.HasMaxLength(25);
#endregion
entity.Property(e => e.ModifiedDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.NameStyle).HasColumnType("NameStyle");
entity.Property(e => e.PasswordHash)
.IsRequired()
.HasMaxLength(128)
.IsUnicode(false);
entity.Property(e => e.PasswordSalt)
.IsRequired()
.HasMaxLength(10)
.IsUnicode(false);
entity.Property(e => e.Rowguid)
.HasColumnName("rowguid")
.HasDefaultValueSql("(newid())");
entity.Property(e => e.SalesPerson).HasMaxLength(256);
entity.Property(e => e.Suffix).HasMaxLength(10);
entity.Property(e => e.Title).HasMaxLength(8);
});
modelBuilder.Entity<CustomerAddress>(entity =>
{
entity.HasKey(e => new { e.CustomerId, e.AddressId });
entity.ToTable("CustomerAddress", "Person");
entity.HasIndex(e => e.Rowguid)
.HasDatabaseName("AK_CustomerAddress_rowguid")
.IsUnique();
entity.Property(e => e.CustomerId).HasColumnName("CustomerID");
entity.Property(e => e.AddressId).HasColumnName("AddressID");
entity.Property(e => e.AddressType)
.IsRequired()
.HasColumnType("Name")
.HasMaxLength(50);
entity.Property(e => e.ModifiedDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.Rowguid)
.HasColumnName("rowguid")
.HasDefaultValueSql("(newid())");
entity.HasOne(d => d.Address)
.WithMany(p => p.CustomerAddress)
.HasForeignKey(d => d.AddressId)
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasOne(d => d.Customer)
.WithMany(p => p.CustomerAddress)
.HasForeignKey(d => d.CustomerId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
//modelBuilder.Entity<ErrorLog>(entity =>
//{
// entity.Property(e => e.ErrorLogId).HasColumnName("ErrorLogID");
// entity.Property(e => e.ErrorMessage)
// .IsRequired()
// .HasMaxLength(4000);
// entity.Property(e => e.ErrorProcedure).HasMaxLength(126);
// entity.Property(e => e.ErrorTime)
// .HasColumnType("datetime")
// .HasDefaultValueSql("(getdate())");
//});
modelBuilder.Entity<Product>(entity =>
{
entity.ToTable("Product", "Production");
entity.HasIndex(e => e.Name)
.HasDatabaseName("AK_Product_Name")
.IsUnique();
entity.HasIndex(e => e.ProductNumber)
.HasDatabaseName("AK_Product_ProductNumber")
.IsUnique();
entity.HasIndex(e => e.Rowguid)
.HasDatabaseName("AK_Product_rowguid")
.IsUnique();
entity.Property(e => e.ProductId).HasColumnName("ProductID");
entity.Property(e => e.Color).HasMaxLength(15);
entity.Property(e => e.DiscontinuedDate).HasColumnType("datetime");
entity.Property(e => e.ListPrice).HasColumnType("money");
entity.Property(e => e.ModifiedDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.Name)
.IsRequired()
.HasColumnType("Name")
.HasMaxLength(50);
entity.Property(e => e.ProductModelId).HasColumnName("ProductModelID");
entity.Property(e => e.ProductNumber)
.IsRequired()
.HasMaxLength(25);
entity.Property(e => e.Rowguid)
.HasColumnName("rowguid")
.HasDefaultValueSql("(newid())");
entity.Property(e => e.SellEndDate).HasColumnType("datetime");
entity.Property(e => e.SellStartDate).HasColumnType("datetime");
entity.Property(e => e.Size).HasMaxLength(5);
entity.Property(e => e.StandardCost).HasColumnType("money");
entity.Property(e => e.Weight).HasColumnType("decimal(8, 2)");
entity.HasOne(d => d.ProductModel)
.WithMany(p => p.Products)
.HasForeignKey(d => d.ProductModelId);
});
modelBuilder.Entity<ProductCategory>(entity =>
{
entity.ToTable("ProductCategory", "Production");
entity.HasIndex(e => e.Name)
.HasDatabaseName("AK_ProductCategory_Name")
.IsUnique();
entity.HasIndex(e => e.Rowguid)
.HasDatabaseName("AK_ProductCategory_rowguid")
.IsUnique();
entity.Property(e => e.ProductCategoryId).HasColumnName("ProductCategoryID");
entity.Property(e => e.ModifiedDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.Name)
.IsRequired()
.HasColumnType("Name")
.HasMaxLength(50);
entity.Property(e => e.Rowguid)
.HasColumnName("rowguid")
.HasDefaultValueSql("(newid())");
});
modelBuilder.Entity<ProductDescription>(entity =>
{
entity.ToTable("ProductDescription", "Production");
entity.HasIndex(e => e.Rowguid)
.HasDatabaseName("AK_ProductDescription_rowguid")
.IsUnique();
entity.Property(e => e.ProductDescriptionId).HasColumnName("ProductDescriptionID");
entity.Property(e => e.Description)
.IsRequired()
.HasMaxLength(400);
entity.Property(e => e.ModifiedDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.Rowguid)
.HasColumnName("rowguid")
.HasDefaultValueSql("(newid())");
});
modelBuilder.Entity<ProductModel>(entity =>
{
entity.ToTable("ProductModel", "Production");
entity.HasIndex(e => e.CatalogDescription)
.HasDatabaseName("PXML_ProductModel_CatalogDescription");
entity.HasIndex(e => e.Name)
.HasDatabaseName("AK_ProductModel_Name")
.IsUnique();
entity.HasIndex(e => e.Rowguid)
.HasDatabaseName("AK_ProductModel_rowguid")
.IsUnique();
entity.Property(e => e.ProductModelId).HasColumnName("ProductModelID");
entity.Property(e => e.CatalogDescription).HasColumnType("xml");
entity.Property(e => e.ModifiedDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.Name)
.IsRequired()
.HasColumnType("Name")
.HasMaxLength(50);
entity.Property(e => e.Rowguid)
.HasColumnName("rowguid")
.HasDefaultValueSql("(newid())");
});
modelBuilder.Entity<ProductModelProductDescription>(entity =>
{
entity.HasKey(e => new { e.ProductModelId, e.ProductDescriptionId, e.Culture });
entity.ToTable("ProductModelProductDescription", "Production");
entity.HasIndex(e => e.Rowguid)
.HasDatabaseName("AK_ProductModelProductDescription_rowguid")
.IsUnique();
entity.Property(e => e.ProductModelId).HasColumnName("ProductModelID");
entity.Property(e => e.ProductDescriptionId).HasColumnName("ProductDescriptionID");
entity.Property(e => e.Culture).HasMaxLength(6);
entity.Property(e => e.ModifiedDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.Rowguid)
.HasColumnName("rowguid")
.HasDefaultValueSql("(newid())");
entity.HasOne(d => d.ProductDescription)
.WithMany(p => p.ProductModelProductDescriptions)
.HasForeignKey(d => d.ProductDescriptionId)
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasOne(d => d.ProductModel)
.WithMany(p => p.ProductModelProductDescriptions)
.HasForeignKey(d => d.ProductModelId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
modelBuilder.Entity<SalesOrderDetail>(entity =>
{
entity.HasKey(e => new { e.SalesOrderId, e.SalesOrderDetailId });
entity.ToTable("SalesOrderDetail", "Sales");
entity.HasIndex(e => e.ProductId);
entity.HasIndex(e => e.Rowguid)
.HasDatabaseName("AK_SalesOrderDetail_rowguid")
.IsUnique();
entity.Property(e => e.SalesOrderId).HasColumnName("SalesOrderID");
entity.Property(e => e.SalesOrderDetailId)
.HasColumnName("SalesOrderDetailID")
.ValueGeneratedOnAdd();
entity.Property(e => e.LineTotal)
.HasColumnType("numeric(38, 6)")
.HasComputedColumnSql("(isnull(([UnitPrice]*((1.0)-[UnitPriceDiscount]))*[OrderQty],(0.0)))");
entity.Property(e => e.ModifiedDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.ProductId).HasColumnName("ProductID");
entity.Property(e => e.Rowguid)
.HasColumnName("rowguid")
.HasDefaultValueSql("(newid())");
entity.Property(e => e.UnitPrice).HasColumnType("money");
entity.Property(e => e.UnitPriceDiscount).HasColumnType("money");
entity.HasOne(d => d.Product)
.WithMany(p => p.SalesOrderDetails)
.HasForeignKey(d => d.ProductId)
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasOne(d => d.SalesOrder)
.WithMany(p => p.SalesOrderDetail)
.HasForeignKey(d => d.SalesOrderId);
});
modelBuilder.Entity<SalesOrderHeader>(entity =>
{
entity.HasKey(e => e.SalesOrderId);
entity.ToTable("SalesOrderHeader", "Sales");
entity.HasIndex(e => e.CustomerId);
entity.HasIndex(e => e.Rowguid)
.HasDatabaseName("AK_SalesOrderHeader_rowguid")
.IsUnique();
entity.HasIndex(e => e.SalesOrderNumber)
.HasDatabaseName("AK_SalesOrderHeader_SalesOrderNumber")
.IsUnique();
entity.Property(e => e.SalesOrderId).HasColumnName("SalesOrderID");
entity.Property(e => e.AccountNumber)
.HasColumnType("AccountNumber")
.HasMaxLength(15);
entity.Property(e => e.BillToAddressId).HasColumnName("BillToAddressID");
entity.Property(e => e.CreditCardApprovalCode)
.HasMaxLength(15)
.IsUnicode(false);
entity.Property(e => e.CustomerId).HasColumnName("CustomerID");
entity.Property(e => e.DueDate).HasColumnType("datetime");
entity.Property(e => e.Freight)
.HasColumnType("money")
.HasDefaultValueSql("((0.00))");
entity.Property(e => e.ModifiedDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.OnlineOrderFlag)
.IsRequired()
.HasColumnType("Flag")
.HasDefaultValueSql("((1))");
entity.Property(e => e.OrderDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.PurchaseOrderNumber)
.HasColumnType("OrderNumber")
.HasMaxLength(25);
entity.Property(e => e.Rowguid)
.HasColumnName("rowguid")
.HasDefaultValueSql("(newid())");
entity.Property(e => e.SalesOrderNumber)
.IsRequired()
.HasMaxLength(25)
.HasComputedColumnSql("(isnull(N'SO'+CONVERT([nvarchar](23),[SalesOrderID],0),N'*** ERROR ***'))");
entity.Property(e => e.ShipDate).HasColumnType("datetime");
entity.Property(e => e.ShipToAddressId).HasColumnName("ShipToAddressID");
entity.Property(e => e.Status).HasDefaultValueSql("((1))");
entity.Property(e => e.SubTotal)
.HasColumnType("money")
.HasDefaultValueSql("((0.00))");
entity.Property(e => e.TaxAmt)
.HasColumnType("money")
.HasDefaultValueSql("((0.00))");
entity.Property(e => e.TotalDue)
.HasColumnType("money")
.HasComputedColumnSql("(isnull(([SubTotal]+[TaxAmt])+[Freight],(0)))");
entity.HasOne(d => d.BillToAddress)
.WithMany(p => p.SalesOrderHeaderBillToAddress)
.HasForeignKey(d => d.BillToAddressId)
.HasConstraintName("FK_SalesOrderHeader_Address_BillTo_AddressID");
entity.HasOne(d => d.Customer)
.WithMany(p => p.SalesOrderHeader)
.HasForeignKey(d => d.CustomerId)
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasOne(d => d.ShipToAddress)
.WithMany(p => p.SalesOrderHeaderShipToAddress)
.HasForeignKey(d => d.ShipToAddressId)
.HasConstraintName("FK_SalesOrderHeader_Address_ShipTo_AddressID");
});
}
}
public class Product
{
public Product()
{
SalesOrderDetails = new HashSet<SalesOrderDetail>();
}
public int ProductId { get; set; }
public string Name { get; set; }
public string ProductNumber { get; set; }
public string Color { get; set; }
public decimal StandardCost { get; set; }
public decimal ListPrice { get; set; }
public string Size { get; set; }
public decimal? Weight { get; set; }
public int? ProductModelId { get; set; }
public DateTime SellStartDate { get; set; }
public DateTime? SellEndDate { get; set; }
public DateTime? DiscontinuedDate { get; set; }
public Guid Rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual ProductModel ProductModel { get; set; }
public virtual ICollection<SalesOrderDetail> SalesOrderDetails { get; set; }
}
public class ProductModel
{
public ProductModel()
{
ProductModelProductDescriptions = new HashSet<ProductModelProductDescription>();
Products = new HashSet<Product>();
}
public int ProductModelId { get; set; }
public string Name { get; set; }
public string CatalogDescription { get; set; }
public Guid Rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual ICollection<ProductModelProductDescription> ProductModelProductDescriptions { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class ProductModelProductDescription
{
public int ProductModelId { get; set; }
public int ProductDescriptionId { get; set; }
public string Culture { get; set; }
public Guid Rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual ProductDescription ProductDescription { get; set; }
public virtual ProductModel ProductModel { get; set; }
}
public class ProductDescription
{
public ProductDescription()
{
ProductModelProductDescriptions = new HashSet<ProductModelProductDescription>();
}
public int ProductDescriptionId { get; set; }
public string Description { get; set; }
public Guid Rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual ICollection<ProductModelProductDescription> ProductModelProductDescriptions { get; set; }
}
public class ProductCategory
{
public ProductCategory()
{
}
public int ProductCategoryId { get; set; }
public string Name { get; set; }
public Guid Rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
}
public class SalesOrderDetail
{
public int SalesOrderId { get; set; }
public int SalesOrderDetailId { get; set; }
public short OrderQty { get; set; }
public int ProductId { get; set; }
public decimal UnitPrice { get; set; }
public decimal UnitPriceDiscount { get; set; }
public decimal LineTotal { get; set; }
public Guid Rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public Product Product { get; set; }
public SalesOrderHeader SalesOrder { get; set; }
}
public partial class SalesOrderHeader
{
public SalesOrderHeader()
{
SalesOrderDetail = new HashSet<SalesOrderDetail>();
}
public int SalesOrderId { get; set; }
public byte RevisionNumber { get; set; }
public DateTime OrderDate { get; set; }
public DateTime DueDate { get; set; }
public DateTime? ShipDate { get; set; }
public byte Status { get; set; }
public bool? OnlineOrderFlag { get; set; }
public string SalesOrderNumber { get; set; }
public string PurchaseOrderNumber { get; set; }
public string AccountNumber { get; set; }
public int CustomerId { get; set; }
public int? ShipToAddressId { get; set; }
public int? BillToAddressId { get; set; }
public string CreditCardApprovalCode { get; set; }
public decimal SubTotal { get; set; }
public decimal TaxAmt { get; set; }
public decimal Freight { get; set; }
public decimal TotalDue { get; set; }
public string Comment { get; set; }
public Guid Rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public Address BillToAddress { get; set; }
public Customer Customer { get; set; }
public Address ShipToAddress { get; set; }
public ICollection<SalesOrderDetail> SalesOrderDetail { get; set; }
}
public class CustomerName
{
public CustomerName()
{
this.Contact = new CustomerContact();
}
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public CustomerContact Contact { get; set; }
}
public class CustomerContact
{
public CustomerContact()
{
}
public string EmailAddress { get; set; }
public string Phone { get; set; }
}
public class Customer
{
public Customer()
{
CustomerAddress = new HashSet<CustomerAddress>();
SalesOrderHeader = new HashSet<SalesOrderHeader>();
this.CustomerName = new CustomerName();
}
public int CustomerId { get; set; }
public bool NameStyle { get; set; }
public string Title { get; set; }
public CustomerName CustomerName { get; set; }
public string Suffix { get; set; }
public string CompanyName { get; set; }
public string SalesPerson { get; set; }
public string PasswordHash { get; set; }
public string PasswordSalt { get; set; }
public Guid Rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
/// <summary>
/// This field is for testing server side calculated fields
/// </summary>
public int? AddressCount { get; set; }
public ICollection<CustomerAddress> CustomerAddress { get; set; }
public ICollection<SalesOrderHeader> SalesOrderHeader { get; set; }
}
public class CustomerAddress
{
public int CustomerId { get; set; }
public int AddressId { get; set; }
public string AddressType { get; set; }
public Guid Rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public Address Address { get; set; }
public Customer Customer { get; set; }
}
public class Address
{
public Address()
{
CustomerAddress = new HashSet<CustomerAddress>();
SalesOrderHeaderBillToAddress = new HashSet<SalesOrderHeader>();
SalesOrderHeaderShipToAddress = new HashSet<SalesOrderHeader>();
}
public int AddressId { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string StateProvince { get; set; }
public string CountryRegion { get; set; }
public string PostalCode { get; set; }
public Guid Rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public ICollection<CustomerAddress> CustomerAddress { get; set; }
public ICollection<SalesOrderHeader> SalesOrderHeaderBillToAddress { get; set; }
public ICollection<SalesOrderHeader> SalesOrderHeaderShipToAddress { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment