开发者

One to one relation with EF 4.1 code first

开发者 https://www.devze.com 2023-03-12 05:17 出处:网络
My question is similar to this one : --> Many to one configuration using EF 4.1 code first There are some fluent API solutions on google, with overriding \"OnModelCreating\" method and manually sett

My question is similar to this one :

--> Many to one configuration using EF 4.1 code first

There are some fluent API solutions on google, with overriding "OnModelCreating" method and manually setting the foreign key options. But i would prefer a solution with data annotations if it is possible. Because I'd like to use inverse properties while coding. Such as TypeA object has got a TypeB object. So TypeB object should have a ParentTypeA property. Examp开发者_StackOverflow社区le :

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


A conventions way to do this in Code First is to use the UserID as the Primary Key of the UserGallery object. This is fine if its a true one to one relationship.

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

This has worked fine for me in the past.

0

精彩评论

暂无评论...
验证码 换一张
取 消