简体   繁体   中英

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

I would like to create an Association Property with the following setup:

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; }
}

My problem is that type2Prop can't find it's foregin key. It is trying to look for "type2Prop_ID", which does not exist, when it should really be looking for "type2_ID". Here is the error I get:

{"Invalid column name 'type2Prop_ID'."}

How do I tell it which property to use as ClassType2's key?

Try a ForeignKeyAttribute on type2Prop :

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; }
}

You can also do it using the Fluent API in a refactor-proof way (ie if you change the name of your property in the future, the compiler will let you know you have to change the mapping as well). It's a bit uglier for simple cases like this, but it's also more robust. In your DbContext class, you could add something like:

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM