此處記錄學習efcore 過程中一些學習筆記:
1.code first 創建數據庫,一對多關係對應爲一個對象擁有一個集合,這個集合使用virtual標識以便使用lazyLoading,另一方面被擁有的對象也有所屬對象及所屬對象ID。多對多關係除了兩個對象分別用擁有對方集合方式表示外,還得有兩個對象關係對象存儲關係所屬對象。類型關係展示如下所示:
一個Customer有多個訂單:
public partial class Customers
{
public Customers()
{
Orders = new HashSet<Orders>();
}
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
[InverseProperty("Customer")]
public virtual ICollection<Orders> Orders { get; set; }
}
一個訂單order屬於一個Customer,並且一個訂單包含多個商品product
public partial class Orders
{
public Orders()
{
ProductOrders = new HashSet<ProductOrders>();
}
[Key]
public int Id { get; set; }
public DateTime OrderPlaced { get; set; }
public DateTime? OrderFulfilled { get; set; }
public int CustomerId { get; set; }
[ForeignKey(nameof(CustomerId))]
[InverseProperty(nameof(Customers.Orders))]
public virtual Customers Customer { get; set; }
[InverseProperty("Order")]
public virtual ICollection<ProductOrders> ProductOrders { get; set; }
}
一個商品product分佈在多個訂單中:
public partial class Products
{
public Products()
{
ProductOrders = new HashSet<ProductOrders>();
}
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Column(TypeName = "decimal(18, 2)")]
public decimal Price { get; set; }
[InverseProperty("Product")]
public virtual ICollection<ProductOrders> ProductOrders { get; set; }
}
此關係對象爲訂單,商品多對多關係對象:
public partial class ProductOrders
{
[Key]
public int Id { get; set; }
public int Quantity { get; set; }
public int ProductId { get; set; }
public int OrderId { get; set; }
[ForeignKey(nameof(OrderId))]
[InverseProperty(nameof(Orders.ProductOrders))]
public virtual Orders Order { get; set; }
[ForeignKey(nameof(ProductId))]
[InverseProperty(nameof(Products.ProductOrders))]
public virtual Products Product { get; set; }
}
code first創建對象之後,得再創建DbContext對象,將那些是表給用DbSet<object>標識出來:
public class ContosoPetsContext:DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductOrder> ProductOrders { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=ContosoPets;Integrated Security=true");
}
}
之後用包管理控制檯輸入命令:Add-Migration InitialCreat 創建對象數據庫。之後Update-Database將更新到數據庫。加字段或者修改字段之後,執行Add-Migration AddOrModifyFiled進行同步更新到數據庫。