代码优先-实体框架-如何公开外键

问题描述:

我有以下数据对象:

public class Customer : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<Customer>
{
    public Customer ()
    {
        // this.HasRequired(a => a.EyeColorType).WithMany().HasForeignKey(a => a.EyeColorTypeID);
    }

    [Key]
    public int ID { get; set; }

    [Required]
    [MaxLength(100)]
    public string FirstName { get; set; }

    [Required]
    [MaxLength(100)]
    public string LastName { get; set; }

    [Required]
    [ForeignKey("EyeColorTypeID")]
    public EyeColorType EyeColorType { get; set; }
    // public int EyeColorTypeID { get; set; }

}

}

我要做的是,在生成的Customer属性上显示字段 EyeColorTypeID ,并在数据库中指定名称。

What I am trying to do, is expose the field EyeColorTypeID on the generated Customer property, as well as specify the name in the DB.

如果我删除两个注释,都可以,但是我想为此使用数据注释。像 [ExposeForeignKey( EyeColorTypeID)] 之类的东西会自动发生。

If I remove both comments, it works, but I would like to use a data annotation for this. Something like [ExposeForeignKey("EyeColorTypeID")] and have it all happen automatically.

这可能吗?我该怎么办?

Is this possible? How would I go about that?

只需将其添加到模型中,并使导航属性为虚拟(用于延迟加载):

Just add it to the model and make the navigation property virtual (for lazy loading):

public class Customer : //etc
{

   //your stuff

   [Required]
   public int EyeColorTypeID {get; set;}

   public virtual EyeColorType EyeColorType { get; set; }
}

EF的命名约定将绑定 EyeColorTypeID EyeColorType 导航属性。

The naming conventions of EF will bind the EyeColorTypeID to the EyeColorType navigation property.