简体   繁体   English

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

[英]Code First - Entity Framework - How to expose foreign keys

I have the following data object: 我有以下数据对象:

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

}

} }

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. 我想要做的是,在生成的Customer属性上公开EyeColorTypeID字段,并在DB中指定名称。

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. [ExposeForeignKey("EyeColorTypeID")] ,让它全部自动发生。

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

The naming conventions of EF will bind the EyeColorTypeID to the EyeColorType navigation property. EF的命名约定将EyeColorTypeID绑定到EyeColorType导航属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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