Entity Framework auto-identifier foreign key attachments

I have 2 User and User_Profile objects (one to one relationships). I linked them as follows:

public class User { [Key] [ForeignKey("user_profile")] public int user_id {get;set;} public string username {get;set;} public string email {get;set;} public virtual User_Proile user_profile {get;set;} } public class User_Profile { [Key] public int user_id {get;set;} public string firstname {get;set;} public string lastname {get;set;} } 

user_id is the PC in both the SQL Server User and User_Profile tables. It is also set as the Identity column in the User table.

When I try to insert a new record through EFDBContext Add / SaveChanges. I get the following error: "user_id cannot be NULL in the table User_Profile". This makes sense since this is a PK column. I was hoping that EF would be able to take the Identity user_id from the Users and Insert it into User_Profile user_id when saving.

Is this possible, and if so, how do I implement this?

UPDATE: Please note: I manually created the tables and classes of the DB code, so I do not have access to StoreGeneratedPattern through the .edmx file.

+6
source share
2 answers

I think you need to set up a one-to-one relationship using the Fluent API:

 public class MyContext : DbContext { // ... your DbSets protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<User>() .HasRequired(u => u.user_profile) .WithRequiredPrincipal(); } } 

And entity classes:

 public class User { [Key] public int user_id {get;set;} public string username {get;set;} public string email {get;set;} public virtual User_Profile user_profile {get;set;} } public class User_Profile { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int user_id {get;set;} public string firstname {get;set;} public string lastname {get;set;} } 

You must disconnect DatabaseGeneratedOption from Identity to None in one of the classes. I changed the primary and the dependent, as it seems that User should be primary. [ForeignKey(...)] not required because EF recognizes user_id in User_Profile as the FK property for User .

Code like this ...

 using (var context = new MyContext()) { var user = new User(); var userProfile = new User_Profile(); user.user_profile = userProfile; context.Users.Add(user); context.SaveChanges(); } 

... should work when you expect, and save both related objects in the database.

+7
source

You need to set the StoreGeneratedPattern attribute to Authentication in your .edmx file to let the framework know that the field is created by the database. This link may help ...

Standalone Entity Infrastructure Room

0
source

Source: https://habr.com/ru/post/900316/


All Articles