In my data model (Entity Framework 6.1.3, ASP.NET MVC 5, Code First with an existing database) there a two tables, “Person” and “User” that share a one-to-one relationship. “User” table has as PK the PersonID column which is in turn the “Person” table's PK. I’d like whenever a new User record is created, a Person record be (first) automatically created and then the value of PersonID in Person table get inserted into the new User record.
This is the model code for Person table:
[Table("Person")]
public partial class Person
{
public int PersonID { get; set; }
public virtual User User { get; set; }
}
This is the model code for User table:
[Table("User")]
public partial class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int PersonID { get; set; }
[Required]
[StringLength(20)]
public string Name { get; set; }
public virtual Person Person { get; set; }
}
The UserController.cs code includes:
// POST: User/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PersonID,Name")] User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.PersonID = new SelectList(db.People, "PersonID", "PersonID", user.PersonID);
return View(user);
}
The SQL for the Person table:
CREATE TABLE [dbo].[Person](
[PersonID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL
CONSTRAINT [PK_Person_PersonID] PRIMARY KEY CLUSTERED)
The SQL for the User table:
CREATE TABLE [dbo].[User](
[PersonID] [int] NOT NULL,
[Name] [nvarchar](20) NOT NULL
CONSTRAINT [PK_User_PersonID] PRIMARY KEY CLUSTERED)
ALTER TABLE [dbo].[User] WITH CHECK ADD CONSTRAINT [FK_User_Person_PersonID] FOREIGN KEY([PersonID])
REFERENCES [dbo].[Person] ([PersonID])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_User_Person_PersonID]
GO
Thanks in advance, galaf.