簡體   English   中英

在實體框架中,如何在代碼中創建關聯屬性?

[英]In Entity Framework, how do I create an Association Property in code?

我想使用以下設置創建一個關聯屬性:

public class ClassType1{
    [Key]
    public int type1_ID { get;set; }
    public int type2_ID { get;set; }  // In database, this is a foreign key linked to ClassType2.type2_ID
    public ClassType2 type2Prop { get;set; }
}

public class ClassType2{
    [Key]
    public int type2_ID { get;set; }
}

我的問題是type2Prop無法找到它的foregin密鑰。 當它應該真正尋找“type2_ID”時,它試圖尋找不存在的“type2Prop_ID”。 這是我得到的錯誤:

{"Invalid column name 'type2Prop_ID'."}

如何告訴它使用哪個屬性作為ClassType2的鍵?

type2Prop上嘗試ForeignKeyAttribute

using System.ComponentModel.DataAnnotations.Schema;

public class ClassType1
{
  [Key]
  public int type1_ID { get; set; }

  public int type2_ID { get; set; }  // In database, this is a foreign key linked to ClassType2.type2_ID

  [ForeignKey("type2_ID")]
  public virtual ClassType2 type2Prop { get; set; }
}

public class ClassType2
{
  [Key]
  public int type2_ID { get;set; }
}

您也可以使用Fluent API以防重構方式執行此操作(即,如果您將來更改屬性的名稱,編譯器將告知您還必須更改映射)。 對於像這樣的簡單案例來說,它有點丑陋,但它也更強大。 在您的DbContext類中,您可以添加如下內容:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<ClassType1>().HasRequired(x => x.type2Prop)
                                   .WithMany()
                                   .HasForeignKey(x => x.type2_ID);
}
public class ClassType1{
    [Key]
    public int type1_ID { get;set; }
    [ForeignKey("type2Prop")]
    public int type2_ID { get;set; }  // In database, this is a foreign key linked to ClassType2.type2_ID
    public ClassType2 type2Prop { get;set; }
}

public class ClassType2{
    [Key]
    public int type2_ID { get;set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM