复合键作为外键

我在MVC 3应用程序中使用Entity Framework 4.1。我有一个实体,我的主键由两列组成(复合键)。这在另一个实体中用作外键。如何建立关系?在普通的scnerios中,我们使用:


public class Category

{

    public string CategoryId { 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 string CategoryId { get; set; }


    public virtual Category Category { get; set; }

但是如果category有两列键怎么办?


LEATH
浏览 551回答 2
2回答

慕田峪9158850

您可以使用任何一种流畅的API:public class Category{&nbsp; &nbsp; public int CategoryId1 { get; set; }&nbsp; &nbsp; public int CategoryId2 { get; set; }&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; public virtual ICollection<Product> Products { get; set; }}public class Product{&nbsp; &nbsp; public int ProductId { get; set; }&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; public int CategoryId1 { get; set; }&nbsp; &nbsp; public int CategoryId2 { get; set; }&nbsp; &nbsp; public virtual Category Category { get; set; }}public class Context : DbContext{&nbsp; &nbsp; public DbSet<Category> Categories { get; set; }&nbsp; &nbsp; public DbSet<Product> Products { get; set; }&nbsp; &nbsp; protected override void OnModelCreating(DbModelBuilder modelBuilder)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; base.OnModelCreating(modelBuilder);&nbsp; &nbsp; &nbsp; &nbsp; modelBuilder.Entity<Category>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .HasKey(c => new {c.CategoryId1, c.CategoryId2});&nbsp; &nbsp; &nbsp; &nbsp; modelBuilder.Entity<Product>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .HasRequired(p => p.Category)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .WithMany(c => c.Products)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .HasForeignKey(p => new {p.CategoryId1, p.CategoryId2});&nbsp; &nbsp; }}或数据注释:public class Category{&nbsp; &nbsp; [Key, Column(Order = 0)]&nbsp; &nbsp; public int CategoryId2 { get; set; }&nbsp; &nbsp; [Key, Column(Order = 1)]&nbsp; &nbsp; public int CategoryId3 { get; set; }&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; public virtual ICollection<Product> Products { get; set; }}public class Product{&nbsp; &nbsp; [Key]&nbsp; &nbsp; public int ProductId { get; set; }&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; [ForeignKey("Category"), Column(Order = 0)]&nbsp; &nbsp; public int CategoryId2 { get; set; }&nbsp; &nbsp; [ForeignKey("Category"), Column(Order = 1)]&nbsp; &nbsp; public int CategoryId3 { get; set; }&nbsp; &nbsp; public virtual Category Category { get; set; }}
打开App,查看更多内容
随时随地看视频慕课网APP