简体   繁体   中英

Entity Framework Parent and Child Save

I've got a Main_User Type, and a Sub_user Type.

Sub User has a main_user_UID foreign key relationship.

I cannot for the life of me get them to insert at the same time because the Main_User UID isn't present when I try to save the Sub_User type.

public class Main_User
{
 [key]
 public int Main_User_UID {get;set;}
 public virtual ICollection<Sub_User> SubUsers{get;set;}
 //others
}

Then my Sub User

public class Sub_User
{
 [key]
 public int Sub_User_UID {get;set;}
 public int Main_User_UID {get;set;}
 public virtual Main_User MainUser{get;set;}
 //others
}

And My Context mappings for that.

modelBuilder.Entity<Main_User>()
            .HasMany(c => c.SubUsers)
            .WithRequired(c => c.Main_User)
            .HasForeignKey(c => c.Main_User_UID)

I've tried a couple other ways I've found, but no matter what It wont fill the Sub_User => Main_User_UID foreign key field on SaveChanges when I add a Sub_User to the Main_User.SubUsers.

I suspect that you are trying to manage your entity relationships directly by their foreign keys. Try something like this instead:

var mainUser = new Main_User{ //field values here }
mainUser.Sub_Users.Add(new Sub_User{ //field values here });
context.Add(mainUser);
context.SaveChanges();

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