复合键作为外键

复合键作为外键,第1张

复合键作为外键

您可以使用任何一种流畅的API:

public class Category{    public int CategoryId1 { get; set; }    public int CategoryId2 { get; set; }    public string Name { get; set; }    public virtual ICollection<Product> Products { get; set; }}public class Product{    public int ProductId { get; set; }    public string Name { get; set; }    public int CategoryId1 { get; set; }    public int CategoryId2 { get; set; }    public virtual Category Category { get; set; }}public class Context : DbContext{    public DbSet<Category> Categories { get; set; }    public DbSet<Product> Products { get; set; }    protected override void onModelCreating(DbModelBuilder modelBuilder)    {        base.onModelCreating(modelBuilder);        modelBuilder.Entity<Category>() .HasKey(c => new {c.CategoryId1, c.CategoryId2});        modelBuilder.Entity<Product>() .HasRequired(p => p.Category) .WithMany(c => c.Products) .HasForeignKey(p => new {p.CategoryId1, p.CategoryId2});    }}

数据注释

public class Category{    [Key, Column(Order = 0)]    public int CategoryId2 { get; set; }    [Key, Column(Order = 1)]    public int CategoryId3 { get; set; }    public string Name { get; set; }    public virtual ICollection<Product> Products { get; set; }}public class Product{    [Key]    public int ProductId { get; set; }    public string Name { get; set; }    [ForeignKey("Category"), Column(Order = 0)]    public int CategoryId2 { get; set; }    [ForeignKey("Category"), Column(Order = 1)]    public int CategoryId3 { get; set; }    public virtual Category Category { get; set; }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5588132.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存