代码优先-实体框架-如何公开外键 [英] Code First - Entity Framework - How to expose foreign keys

查看:41
本文介绍了代码优先-实体框架-如何公开外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据对象:

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.

这篇关于代码优先-实体框架-如何公开外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆