Noldor
Noldor

Reputation: 1182

One to one relation with EF 4.1 code first

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. Example :

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

Upvotes: 0

Views: 657

Answers (1)

Richard Forrest
Richard Forrest

Reputation: 3615

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.

Upvotes: 1

Related Questions