Expanded basic sample

This commit is contained in:
Koen Bekkenutte
2021-05-27 05:45:58 +08:00
parent d7e0ad3738
commit 8c27425955
2 changed files with 71 additions and 9 deletions

View File

@@ -2,27 +2,60 @@
using EntityFrameworkCore.Projections.Extensions;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace BasicSample
{
public partial class User
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Order> Orders { get; set; }
[Projectable]
public string FullName
=> FirstName + " " + LastName;
=> $"{FirstName} {LastName}";
[Projectable]
public string FullNameFunc()
=> FirstName + " " + LastName;
public double TotalSpent => Orders.Sum(x => x.PriceSum);
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public int ProductId { get; set; }
public ICollection<OrderItem> Items { get; set; }
[Projectable]
public double PriceSum => Items.Sum(x => x.TotalPrice);
}
public class OrderItem
{
public int OrderId { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public double UnitPrice { get; set; }
public Order Order { get; set; }
public Product Product { get; set; }
[Projectable]
public double TotalPrice => Quantity * UnitPrice;
}
public class ApplicationDbContext : DbContext
@@ -31,6 +64,11 @@ namespace BasicSample
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<OrderItem>().HasKey(x => new { x.OrderId, x.ProductId });
}
public DbSet<User> Users { get; set; }
}
@@ -53,7 +91,29 @@ namespace BasicSample
var dbContext = serviceProvider.GetRequiredService<ApplicationDbContext>();
dbContext.Database.EnsureCreated();
var user = new User { FirstName = "Jon", LastName = "Doe" };
var product1 = new Product { Name = "Red pen", Price = 1.5 };
var product2 = new Product { Name = "Blue pen", Price = 2.1 };
var user = new User {
FirstName = "Jon",
LastName = "Doe",
Orders = new List<Order> {
new Order {
Items = new List<OrderItem> {
new OrderItem {
Product = product1,
UnitPrice = product1.Price,
Quantity = 1
},
new OrderItem {
Product = product2,
UnitPrice = product2.Price,
Quantity = 2
}
}
}
}
};
dbContext.Users.Add(user);
@@ -61,9 +121,10 @@ namespace BasicSample
var query = dbContext.Users
.Select(x => new {
Foo = x.FullNameFunc()
Name = x.FullName,
x.TotalSpent
});
Console.WriteLine(query.ToQueryString());
var r1 = query.ToArray();