新建类库Models,加入以下三个类:
Product:
public class Product { /// <summary> /// 编号 /// </summary> public int Id { get; set; } /// <summary> /// 名称 /// </summary> public string Name { get; set; } /// <summary> /// 型号 /// </summary> public string Code { get; set; } /// <summary> /// 单价 /// </summary> public double Price { get; set; } /// <summary> /// 单位 /// </summary> public string Unit { get; set; } /// <summary> /// 数量 /// </summary> public double Count { get; set; } /// <summary> /// 最后更新时间 /// </summary> public DateTime LastUpdateTime { get; set; } }
Purchase:
public class Purchase { /// <summary> /// 编号 /// </summary> public int Id { get; set; } /// <summary> /// 产品编号 /// </summary> public int ProductId { get; set; } /// <summary> /// 单价 /// </summary> public double Price { get; set; } /// <summary> /// 数量 /// </summary> public double Count { get; set; } /// <summary> /// 总价 /// </summary> public double TotalPrice { get; set; } /// <summary> /// 实际总价 /// </summary> public double ActualPrice { get; set; } /// <summary> /// 创建时间 /// </summary> public DateTime CreateTime { get; set; } public virtual Product Product { get; set; } }
Sale:
public class Sale { /// <summary> /// 编号 /// </summary> public int Id { get; set; } /// <summary> /// 产品编号 /// </summary> public int ProductId { get; set; } /// <summary> /// 单价 /// </summary> public double Price { get; set; } /// <summary> /// 数量 /// </summary> public double Count { get; set; } /// <summary> /// 总价 /// </summary> public double TotalPrice { get; set; } /// <summary> /// 实际总价 /// </summary> public double ActualPrice { get; set; } /// <summary> /// 创建时间 /// </summary> public DateTime CreateTime { get; set; } public virtual Product Product { get; set; } }
通过nuget引入EF:
install-package entityframework
如果属性名为 Id 或 <类名>Id. Code-First 会自动以此创建主键.主键可以是任意类型, 如果主键是数字型或者GUID,会配置成自动增长或自动生成.
但如果像下面这样定义类的话就会报错:
public class Product {public int PId { get; set; } public string Name { get; set; } }
在Purchases类中,定义了Product的关联,
public int ProductId { get; set; } public virtual Product Product { get; set; }
EF会自动为在Purchases中创建ProductId 外键:
在迁移代码中可以看到:
public partial class PurchaseChange : DbMigration { public override void Up() { CreateIndex("dbo.Purchases", "ProductId"); AddForeignKey("dbo.Purchases", "ProductId", "dbo.Products", "Id", cascadeDelete: true); } public override void Down() { DropForeignKey("dbo.Purchases", "ProductId", "dbo.Products"); DropIndex("dbo.Purchases", new[] { "ProductId" }); } }
Sales类也添加了ProductId的外键,这样在创建Sale时如果新增Product的话,会自动把新增Product的Id赋值到Sale里的ProductId上:
using (var ctx = new SalesContext()) { Product p1 = new Product() { Name = "腐竹", Code = "002", Price = 3, Count = 100, Unit = "g", LastUpdateTime = DateTime.Now }; ctx.Products.Add(p1); Sale s1 = new Sale() { Price = 5, Count = 10, TotalPrice = 50, ActualPrice = 50, CreateTime = DateTime.Now,Product=p1 }; ctx.Sales.Add(s1); ctx.SaveChanges(); }
时间: 2024-10-11 11:29:52