0

I have two entities. User and UserContacts.

I have created two classes. User

public class PUser
{
    public int PUserId { get; set; }

    public virtual UserContact UserContact { get; set; }
}

public class UserContact
{
    public int UserContactId { get; set; }

    public virtual PUser PUser { get; set; }
}

I may have multiple user contacts but In my MVC view - I want to add only one user contact.

How can I do that? Above is creating tables but not inserting Puserid in user contact table.

Fluent api used is.

 modelBuilder.Entity<PUser>()
                .HasOptional(p => p.UserContact).WithRequired(p => p.PUser);
6
  • Can you be more specific about what the problem is? Your primary key is missing from the insert? Commented May 16, 2013 at 18:30
  • Yes, When I do insert. It inserts user contacts but userid goes null. Commented May 16, 2013 at 18:39
  • Show your code which inserts data. Commented May 16, 2013 at 18:45
  • 1
    Wrote an answer but I don't think your yes was actually a yes. Post your code that adds the item to the DB. Commented May 16, 2013 at 18:46
  • Did you check PUsers table for UserContact_Id field? Commented May 16, 2013 at 19:18

1 Answer 1

1

This is a one-to-one relationship, so you need to initialize your UserContact when you create User. This is how i would do it.

    [HttpGet]
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(PUser model)//You should use a ViewModel here
    {
        if (ModelState.IsValid)
        {
            var db = new EfDb(); // If you introduce abstration to you Context, you could avoid this.               
            var user= new PUser
                             {   
                                 Name = model.Name,                                             
                                 UserContact= new UserContact
                                                    {
                                                       Phone = model.UserContact.Phone             
                                                    }
                              };

             db.PUser.Add(user);
             db.SaveChanges();
             return RedirectToAction("Index", "Home");
         }                        
        return View(model);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.