简体   繁体   中英

Unable to map one to one in Entity Framework 6

I'm having trouble mapping a one to one relationship in EF 6. My classes are:

public class Membership
{
     [Key]
     public decimal Id { get; set; }

     [ForeignKey("Id")]
     public virtual User User { get; set; }
}

public class User
{
     [Key]
     public decimal Id { get; set; }

     [ForeignKey("Id")]
     public virtual Membership Membership { get; set; }

}

I am getting the exception:

Unable to determine the principal end of an association between the types 'User' and 'Membership'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

I think my issue is both tables has the same key value and do not store the key of the other. Thanks.

This will work

public class Membership
{
 [Key]
 public decimal Id { get; set; }

 [ForeignKey("User")]
 public decimal UserId {get;set;}
 public virtual User User { get; set; }
}

public class User
{
 [Key]
 public decimal Id { get; set; }

 [ForeignKey("Membership ")]
 public decimal MemberShipId {get;set;}
 public virtual Membership Membership { get; set; }

}

You should refer to this thread per ladislav, I'll put the contents here as well though.

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.

In case of entity framework FK in dependent must also be its PK so in your case you should use:

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or using fluent mapping:

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);

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