简体   繁体   中英

Entity Framework Code First : One-To-One association using Annotations

I am having .NET MVC 5 and Identity... I am trying to get a one to one relationship for my Member class to my MemberInfo class.. So, My classes looks something like this:

IdentityUser is in the Microsoft.AspNet.Identity.EntityFramework namespace with string Id as its ID.

public class GRNUser : IdentityUser {
    ....
    .... 
}


public class MemberUser : GRNUser {
    public virtual Member MemberInfo {get; set; }
}

public class Member { 
    public int ID {get; set; }
    public string MemberUserID {get; set; }

    public virtual MemberUser MemberUser { get; set; }
}

In my Context, I have this

modelBuilder.Entity<Member>().HasRequired(m => m.MemberUser)
                             .WithOptional(u => u.MemberInfo);

So, the MemberUser and Member should be able to navigate to and from each other using the MemberUser's ID property and Member's MemberUserID property.

However, when my Database is created, it has an additional column "MemberUser_Id" instead of using my MemberUserID that I specified. How do I make it use "MemberUserID" that I specified?

I've tried using a few combination so of the ForiegnKey Data Annotation, but keeps on getting this error: Member_MemberUser_Source: : Multiplicity is not valid in Role 'Member_MemberUser_Source' in relationship 'Member_MemberUser'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

I don't know whether i understood you right or not, but i'l do my best to help. (I'l assume that you work with code first migration)

If you want to make a one-to-one relation, why not try to make a standalone entity for your info which will have a foreign key for the user entity and that foreign key will be annotated as the primary key of the entity?

Another way is why just not add whatever attributes you like to the Application User entity and work with it?

In any case i might have misunderstood your purpose, so please feel free to explain further since your post is a bit confusing.

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