Create New Record in MVC Controller database entity-framework


I am using c# MVC I am trying to create 2 new records in 2 tables - employee and address table. I have the following so far:


When an employee record is created, it creates an EmpID record which is autogenerated. I need to get that EmpID and create a new record in the address table with that EmpID as as there is a primary foreign key relationship between the 2 tables.

I am not sure how to get the EmpID from employee table and then create a new record for the address table. I thought I could get it after AddObject but it did not create an employee record.

11/30/2011 4:38:01 PM

Accepted Answer

I know you're not supposed to just give feedback, but in this case, this answer is right on, no need to go further. If you create a model, using a database table, as long as that database table has an ID field. It will create the get/set methods for you. In mine, it even created a more elaborate get/set method probably because the name of my ID field is ProdID. But you can expand the model.cs file, (after you create the model from the database) and see the get/set method these guys are talking about. In the case you are using a GUID you can just use

card.Guid = Guid.NewGuid();

The NewGuid() method in the controller create function.

8/26/2012 1:21:46 AM

Popular Answer

I assume you are using Entity Framework given the code you are providing. You should set up a relationship between your two entities and let EF handle this for you:

public class Employee {
    public int EmployeeId { get; set; }
    public virtual Address Address { get; set; }

public class Address {
    public int AddressId { get; set; }
    public int EmployeeId { get; set; }
    public virtual Employee Employee { get; set; }

Now when you create the entities:

// create a new Employee
Employee employee = new Employee(); 

// create a new Address
Address address = new Address();

// associate the address with the new employee
employee.Address = address;

// add the employee to the data context

// when you call save changes, since your Address is attached to your
// employee, it will get added for you and you don't have to add it to the
// context yourself. Entity Framework will save the Employee, get the ID
// from this table and then add a new Address record using the ID that was
// just inserted. 

It will add both objects and add the foreign key for you.


This is a code first example. If you are using Database first using the designer, just set up the relationship using the designer. The code to add the employee shouldn't change in this case.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow