Entity Framework Foreign Key Inserts with Auto-Id

前端 未结 2 905
野趣味
野趣味 2021-02-09 04:42

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

public class User
{
   [Key]   
   [ForeignKey(\"user_profile\"         


        
2条回答
  •  伪装坚强ぢ
    2021-02-09 05:04

    I think it is necessary to configure your one-to-one relationship explicitely using Fluent API:

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

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

    It's necessary to switch off DatabaseGeneratedOption from Identity to None in one of the classes. I have swapped principal and dependent as it seems that the User should be the principal. The [ForeignKey(...)] is not necessary because EF will recognize user_id in User_Profile as a FK property to User.

    A 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 then as you expect and save both related entities to the database.

提交回复
热议问题