简体   繁体   中英

Can't save nested object in entity framework

I'm new in Asp.Net MVC. I use standart Membership provider in my project. I have Application User and ApplicationDbContext

  public class ApplicationUser : IdentityUser
    {
    [Required]
        public virtual UserInfo UserInfo { get; set; }
        public virtual ICollection<Lot> Lots { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public DbSet<Lot> Lots { get; set; }
        public DbSet<Product> Products { get; set; }

        public DbSet<UserInfo> UserInfoes { get; set; }

        public DbSet<PersonalInformation> PersonalInformations { get; set; } 
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }

and UserInfo

public class UserInfo
    {
        [Key]
        public int UserInfoId { get; set; }
        public DateTime RegistarationDate { get; set; }
        public decimal Money { get; set; }
        public decimal CurrentDebt { get; set; }
        public virtual PersonalInformation PersonalInformation { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
    }

Personal Information

 public class PersonalInformation
    {
        public int PersonalInformationId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Telephone { get; set; }
        public Adress Adress { get; set; }
    }

my RegisterViewModel

public class RegisterViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public decimal Money { get; set; }

        public string Telephone { get; set; }
    }

and action create in controller

 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser()
                {
                    UserName = model.UserName,
                    UserInfo = new UserInfo()
                    {
                        CurrentDebt = 0,
                        Money = model.Money,
                        RegistarationDate = DateTime.Now,
                        PersonalInformation = new PersonalInformation()
                        {
                            FirstName = model.FirstName,
                            LastName = model.LastName,
                            Telephone = model.Telephone,
                        }
                    }
                };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

And when I fill all fields that're mentioned in action, i receivee this error

Cannot insert the value NULL into column 'UserInfoId', table 'DefaultConnection.dbo.UserInfoes'; column does not allow nulls. INSERT fails. The statement has been terminated.

Could anybody help me? Thanks a lot

You need to tell EF that UserInfoId is a Key against the table so it maps it as an Identity .

Something like this would work in a mapping file:

public class UserInfoMap : EntityTypeConfiguration<UserInfo>
{
    public UserInfoMap()
    {
        ToTable("UserInfo");
        HasKey(m => m.UserInfoId );
    }
}

When the code first migration runs, it generates something like this:

CreateTable(
    "dbo.UserInfo",
    c => new
        {
            UserInfoId = c.Int(nullable: false, identity: true)
)

which means you won't need to specify the Id as it will auto populate in the database.

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