繁体   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