首先与EF 4.1代码建立一对一的关系

时间:2011-06-10 14:21:17

标签: entity-framework-4.1 code-first one-to-one

我的问题与此类似:

- > Many to one configuration using EF 4.1 code first

Google上有一些流畅的API解决方案,重写“OnModelCreating”方法并手动设置外键选项。但是如果有可能的话,我更喜欢带有数据注释的解决方案。因为我想在编码时使用反向属性。比如TypeA对象有一个TypeB对象。所以TypeB对象应该有一个ParentTypeA属性。示例:

public class User : IUser
{
    [Key(), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    [RegularExpression(@"[A-Za-z0-9_\-\.]{2,32}"), MinLength(2), MaxLength(32)]
    [Required(AllowEmptyStrings = false)]
    public string UserName { get; set; }

   // other props ....
   // ....

    public virtual UserGallery Gallery { get; set; }
}

public class UserGallery : IUserGallery
{
    [Key(), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserGalleryId { get; set; }

   // other props ....
   // ....

    public virtual User ParentUser { get; set; }
}

1 个答案:

答案 0 :(得分:1)

在Code First中执行此操作的约定方法是使用UserID作为UserGallery对象的主键。如果这是真正的一对一关系,这很好。

public class UserGallery : IUserGallery
{
   [Key]
   public int UserId {get;set;}
   public User User {get;set;}
   etc...
}

过去这对我来说很好。

相关问题