Reputation: 102
I have created one asp.net mvc web api using Entity framework model, Which can update Single table in Single request. What i want is to update two tables(Having foreign key relationship) in single POST Request.
How I can achieve this?
What I have Done:-
1.Created Two Table tblEmployeeRecord & tblCountryName in sql server with EmployeeId as a primary key & foreign key respectively. 2.Employee table Model:-
public partial class tblEmployeeRecord
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string userName { get; set; }
public string userRole { get; set; }
}
3.Country Name table Model:-
public partial class tblCountryName
{
public int CountryId { get; set; }
public int EmployeeId { get; set; }
public string Country_Name { get; set; }
}
4.Created wrapper Model as follow:-
public class UserAndCountry
{
public tblEmployeeRecord UserRecord { get; set; }
public tblCountryName CountryRecord { get; set; }
}
5.ActionResult Method in Controller Which handles post request:-
[ResponseType(typeof(UserAndCountry))]
public IHttpActionResult PosttblEmployeeRecord(UserAndCountry tblEmployeeRecord)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.tblCountryNames.Add(tblEmployeeRecord.CountryRecord);
db.tblEmployeeRecords.Add(tblEmployeeRecord.UserRecord);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = tblEmployeeRecord.UserRecord.EmployeeId }, tblEmployeeRecord);
}
6.Note:-What is Happening:-
When I don't define foreign key relationship in SQL Server between these two table, I am able to update both table but when i define foreign key relationship I am not able to update these tables
What will be my request object in that case, Where I am going wrong?
7.My Current Request object:-
{
"CountryRecord":
{
"Country_Name": "AP"
},
"UserRecord":
{
"Name": "Test User",
"userName": "[email protected]",
"userRole": "Hr"
}
}
Upvotes: 0
Views: 2554
Reputation: 12324
The power of entity framework is the navigation properties for relationships. So say your models were:
public partial class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string userName { get; set; }
public string userRole { get; set; }
// Foreign Key
public int CountryId { get; set; }
// Navigation Property
public virtual Country EmployeeCountry
}
public partial class Country
{
public int CountryId { get; set; }
public string Country_Name { get; set; }
}
Now your update becomes:
var employeeRecord = tblEmployeeRecord.UserRecord;
// add the country. EF will make the relationship automagically
employeeRecord.EmployeeCountry = tblEmployeeRecord.CountryRecord;
db.Employees.Add(employeeRecord);
db.SaveChanges();
Upvotes: 1