Code First - Entity Framework - How to expose foreign keys

爱⌒轻易说出口 提交于 2019-12-11 12:47:53

问题


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.

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?


回答1:


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.



来源:https://stackoverflow.com/questions/20081868/code-first-entity-framework-how-to-expose-foreign-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!