为了账号安全,请及时绑定邮箱和手机立即绑定

复合键作为外键

复合键作为外键

C#
LEATH 2019-12-20 10:51:39
我在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有两列键怎么办?
查看完整描述

2 回答

?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

您可以使用任何一种流畅的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; }

}


查看完整回答
反对 回复 2019-12-20
  • 2 回答
  • 0 关注
  • 521 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信