简体   繁体   中英

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.

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

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

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