亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

復合鍵作為外鍵

復合鍵作為外鍵

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條經驗 獲得超8個贊

您可以使用任何一種流暢的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 關注
  • 580 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號