FOREIGN_KEY constraint exception - c#

I have an asp.net application with a c# code-behind, connected to an SQL db with linq-to-entities... When I attempt to 'SaveChanges()' on the following code I get an exception (listed below). Any thoughts on what is up?
private void setNewRide(long newRideID, int carNum)
{
handleCompletedRide(carNum);
using (myEntities = new RamRideOpsEntities())
{
Vehicle assignedCar = myEntities.Vehicles.FirstOrDefault(car => car.CarNum == carNum);
Ride newRide = myEntities.Rides.FirstOrDefault(ride => ride.identity == newRideID);
if (assignedCar != null && newRide != null)
{
vs_CurrentRideId = newRide.identity; //Save current ride to ViewState
vs_CarStatus = assignedCar.Status; //Save old status to ViewState
assignedCar.Status = "EnRoute";
assignedCar.CurrPassengers = newRide.NumPatrons;
assignedCar.StartAdd = newRide.PickupAddress;
assignedCar.EndAdd = newRide.DropoffAddress;
assignedCar.CurrentAdd = newRide.DropoffAddress;
assignedCar.Rides.Add(newRide);
newRide.TimeDispatched = DateTime.Now;
newRide.WaitTime = (((DateTime)newRide.TimeDispatched) - ((DateTime)newRide.TimeOfCall));
newRide.AssignedCar = carNum;
newRide.Status = "EnRoute";
myEntities.SaveChanges(); //EXCEPTION HERE!
SelectCarUP.DataBind();
SelectCarUP.Update();
}
}
}
THE EXCEPTION:
The UPDATE statement conflicted with the FOREIGN KEY constraint
\"FK_Rides_Vehicles\". The conflict occurred in database
\"CWIS29RamRideOps\", table \"dbo.Vehicles\", column
'Identity'.\r\nThe statement has been terminated.
THE DB:

This line:
assignedCar.Rides.Add(newRide);
is translated as SQL-INSERT - while you already have a record with the same ID. Decide what you want to do: insert a new ride (in which case you should NULLify the id of newRide), or update it (in which case you should just comment that line out; changes will be saved).

Change your code like this:
newRide.TimeDispatched = DateTime.Now;
newRide.WaitTime = (((DateTime)newRide.TimeDispatched) - ((DateTime)newRide.TimeOfCall));
newRide.AssignedCar = carNum;
newRide.Status = "EnRoute";
assignedCar.Status = "EnRoute";
assignedCar.CurrPassengers = newRide.NumPatrons;
assignedCar.StartAdd = newRide.PickupAddress;
assignedCar.EndAdd = newRide.DropoffAddress;
assignedCar.CurrentAdd = newRide.DropoffAddress;
assignedCar.Rides = newRide; // Your First Change here
myEntities.SaveChanges();

Related

DbUpdateException Whiles updating record using LINQ to Database

I have been trying to update a record in the database in window form but each time I click the update button I get this error.
System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.' SqlException: Violation of PRIMARY KEY constraint 'PK_ad_gb_rsm'. Cannot insert duplicate key in object 'dbo.ad_gb_rsm'. The duplicate key value is (100001).
The statement has been terminated.
Below is the LINQ code I am using
private void btu_Update_Click(object sender, EventArgs e)
{
if (radioButtonMale.Checked)
{
gender = "male";
}
else if (radioButtonFemale.Checked)
{
gender = "female";
}
userID = Convert.ToDecimal(txtUserID.Text);
//ad_gb_rsm acc = DBS.ad_gb_rsm.First(s => s.ICube_id.Equals(userID));
var query = (from upd in DBS.ad_gb_rsm where upd.ICube_id == userID select upd).ToList();
foreach (var acc in query)
{
acc.user_type = comboBoxUser_Type.Text;
acc.JDate = dateTimeCrtDate.Text;
acc.title = comboBoxTitle.Text;
acc.fName = txtFname.Text;
acc.mName = txtMName.Text;
acc.lName = txtLName.Text;
acc.DOB = dateTimeDOB.Value.ToString();
acc.Gender = gender;
acc.Phone = txtPhoneNumber.Text;
acc.zip_code = txtZipCode.Text;
acc.POB = txtPOBAddress.Text;
acc.address = txtAddress.Text;
acc.email = txtEmail.Text;
acc.City = txtCity.Text;
acc.State = txtState.Text;
acc.marrital_Status = comboBoxMS.Text;
acc.NOK_Name = txtNKName.Text;
acc.NOK_Phone = txtNKNumber.Text;
acc.NOK_Address = txtNOKAddress.Text;
acc.NOKRela = txtNOKRela.Text;
acc.create_dt = dateTimeCrtDate.Value.ToString();
Image img = LogUserImage.Image;
if (img.RawFormat != null)
{
if (ms != null)
{
img.Save(ms, img.RawFormat);
acc.Picture = ms.ToArray();
}
}
acc.Dept_Sector = comboBoxDeptSector.Text;
acc.Position = comboBoxPosition.Text;
acc.JDate = dateTimeJoinDt.Value.ToString();
acc.Empl_Status = comboBoxUserStatus.Text;
acc.username = txtUsername.Text;
acc.password = txtPassword.Text;
acc.incu_copany_name = txtIncu_CompanyName.Text;
acc.createdBy = AdministratorBankLogin.AdminUserLogin.Username;
try
{
DBS.ad_gb_rsm.Add(acc);
DBS.SaveChanges();
MessageBox.Show("User Created Successfully");
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
}
I do not know what I am doing wrong. I am new to this.
The inner exception says everything:
SqlException: Violation of PRIMARY KEY constraint 'PK_ad_gb_rsm'. Cannot insert duplicate key in object 'dbo.ad_gb_rsm'. The duplicate key value is (100001)
Your code tried to perform an INSERT operation, but failed because it violates the unique constraint of the primary key.
The root cause of your problem is the following line:
DBS.ad_gb_rsm.Add(acc);
Because of the Add call your acc entity's state become Added rather than Modified. If you delete that Add method call then it will treat that entity as Modified and will perform an UPDATE operation.
If this change tracking concept is new to you then please read this MDSN article.

How to overwrite data in the database? [ASP.NET]

This code saves my data to the database. The app records the time spent on each day of the month.
They write to the database in SQL Server, using EF. The problem is just that I would like them to overwrite instead of writing more
Controller:
List<Karta_Model> objNextKartaModel = new List<Karta_Model>();
for (int i = 0; i < liczbaDni; i++)
{
var modelNext = new Karta_Model()
{
Login = userName,
Rok = numerRoku,
Miesiac = numerMiesiaca,
DzMiesiaca = modelKarta.Model1[i].DzMiesiaca.Value,
DzTygodnia = modelKarta.Model1[i].DzTygodnia,
Rozpoczecie = modelKarta.Model1[i].Rozpoczecie
....
};
objNextKartaModel.Add(modelNext);
await _ecpContext.Karta.AddRangeAsync(objNextKartaModel);
await _ecpContext.SaveChangesAsync();
}
Id in SQL Server is defined as:
[Id] [int] IDENTITY(1,1)
I came up with the idea to extract the first row ID from the previously saved database
var nrIdBase = _ecpContext.Karta
.FirstOrDefault(f => f.DzMiesiaca == 1 &&
f.Miesiac == numerMiesiaca &&
f.Rok == numerRoku &&
f.Login == userName).Id;
but I don't know how to use it.
I tried something like this:
for (int i = 0; i < liczbaDni; i++)
{
var modelNext = new Karta_Model()
{
Id = nrIdBase +i,
Login = userName,
Rok = numerRoku,
Miesiac = numerMiesiaca,
DzMiesiaca = modelKarta.Model1[i].DzMiesiaca.Value,
DzTygodnia = modelKarta.Model1[i].DzTygodnia,
Rozpoczecie = modelKarta.Model1[i].Rozpoczecie
....
};
}
but I get an error:
InvalidOperationException: The instance of entity type 'Karta_Model' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
Does anyone have an idea how to do this?
How to overwrite saved data once?
In order to update an existing recording in a database, you need to have it's ID before the update operation.
Then you can do this:
var existingRecord = _ecpContext.Karta.FirstOrDefault(x => x.Id == theExistingId);
if (existingRecord != null) {
existingRecord.Login = "CHANGED";
await _ecpContext.SaveChangesAsync()
}
This call that you are using:
await _ecpContext.Karta.AddRangeAsync(objNextKartaModel);
Is only for adding new items to the database.
Following the idea in my comment above, one thing you can do is to delete the existing data in the table before adding the new ones.
List<Karta_Model> objNextKartaModel = new List<Karta_Model>();
for (int i = 0; i < liczbaDni; i++)
{
var modelNext = new Karta_Model()
{
Login = userName,
Rok = numerRoku,
Miesiac = numerMiesiaca,
DzMiesiaca = modelKarta.Model1[i].DzMiesiaca.Value,
DzTygodnia = modelKarta.Model1[i].DzTygodnia,
Rozpoczecie = modelKarta.Model1[i].Rozpoczecie
....
};
objNextKartaModel.Add(modelNext);
//Add logic to delete the existing data
foreach(var model in _ecpContext.Karta)
{
_ecpContext.Karta.Remove(model);
}
await _ecpContext.Karta.AddRangeAsync(objNextKartaModel);
await _ecpContext.SaveChangesAsync();//One SaveChanges call is enough to update the database
}

Problem with modifying an MSI database property

I need to modify the UpgradeCode property of the Upgrade MSI table via C#.
This code works ok with other tables' properties, but throws an error when I'm trying to modify these.
using (var database = new Database(TEMPDATABASE, DatabaseOpenMode.Direct))
{
string upgradeCode = Guid.NewGuid().ToString("B").ToUpper();
database.Execute("Update `Upgrade` Set `Upgrade`.`UpgradeCode` = '{0}'", upgradeCode);
}
The error is:
Microsoft.Deployment.WindowsInstaller.InstallerException: 'Function failed during execution.'
I got curious and pillaged github.com - and it giveth the following: Full project - just download it as a whole.
The actual code was (some unicode line feed issues in the file on github.com, I have fixed them up here):
public static void UpdateUpgradeTable(this Database db, Guid upgradeCode)
{
using (View view = db.OpenView("SELECT * FROM `Upgrade`", new object[0]))
{
view.Execute();
using (Record record = view.Fetch())
{
record[1] = upgradeCode.ToString("B").ToUpperInvariant();
view.Replace(record);
}
db.Commit();
}
}
I took the above and made the following mock-up (very ugly, but it worked):
using (Database db = new Database(#"C:\Test.msi", DatabaseOpenMode.Direct))
{
using (View view = db.OpenView("SELECT * FROM `Upgrade`", new object[0]))
{
view.Execute();
using (Record record = view.Fetch())
{
record[1] = "{777888DD-1111-1111-1111-222222222222}";
record[2] = "";
record[3] = "4.0.1";
record[4] = "";
record[5] = "1";
record[6] = "";
record[7] = "WIX_UPGRADE_DETECTED";
view.Replace(record);
}
db.Commit();
using (Record record = view.Fetch())
{
record[1] = "{777888DD-1111-1111-1111-222222222222}";
record[2] = "";
record[3] = "";
record[4] = "4.0.1";
record[5] = "1";
record[6] = "";
record[7] = "WIX_DOWNGRADE_DETECTED";
view.Replace(record);
}
db.Commit();
}
}
The SDK doc says:
UPDATE queries only work on nonprimary key columns.
UpgradeCode is the primary key for the Upgrade table.

How to stop Entity Framework holding on to record from database?

I'm working on ASP.NET Boilerplate. I have the problem where I try to get a record from a table called Buildings and make an update on it. I get the record from database by:
var buildingApp = _buildingsAppService.getBuildingsById(buildingInput);
And after that, I make some changes on the data as follows:
buildingApp.streetName = Request["buildingaddress"];
buildingApp.isInHoush = Convert.ToBoolean(Request["buildingOutput.isInHoush"]);
buildingApp.houshName = Request["HoushName"];
And then copy the buildingApp to another object, which has the same properties, in order to pass the new object to update method as follows:
var updateBuildingInput = new UpdateBuidlingsInput()
{
Id = buildingApp.Id,
buildingID = buildingApp.buildingID,
numOfBuildingUnits = buildingApp.numOfBuildingUnits,
numOfFloors = buildingApp.numOfFloors,
streetName = buildingApp.streetName,
buildingNo = buildingApp.buildingNo,
neighborhoodID = buildingApp.neighborhoodID,
buildingTypeID = buildingApp.buildingTypeID,
GISMAP = buildingApp.GISMAP,
houshProperty = buildingApp.houshProperty,
houshName = buildingApp.houshName,
X = buildingApp.X,
Y = buildingApp.Y,
buildingName = buildingApp.buildingName,
isInHoush = buildingApp.isInHoush,
buildingUsesID = buildingApp.buildingUsesID
};
And the update method is as follows:
_buildingsAppService.update(updateBuildingInput);
The problem is when it executes the previous line, I get the following error:
System.InvalidOperationException: 'Attaching an entity of type 'TaawonMVC.Models.Buildings' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.'
I can see that when I initialize the object updateBuildingInput manually, the update method runs without error. But when it depends on the object obtained from database using buildingApp, the error happens. It seems like the get method gets data from database and keeps holding on to the record from database, and when I try to update the same record, the conflict happens. This is the whole action where all of get and update happens:
public ActionResult UpdateApplication (UpdateApplicationsInput model)
{
var updateApplication = new UpdateApplicationsInput();
updateApplication.buildingId = Convert.ToInt32(Request["buildingnumber"]);
updateApplication.buildingUnitId = Convert.ToInt32(Request["dropDownBuildingUnitApp"]);
//==== get building and unit related to application for update ======
var buildingInput = new GetBuidlingsInput()
{
Id = updateApplication.buildingId
};
var buildingUnitInput = new GetBuildingUnitsInput()
{
Id = updateApplication.buildingUnitId
};
var buildingApp = _buildingsAppService.getBuildingsById(buildingInput);
var buildingUnitApp = _buildingUnitsAppService.GetBuildingUnitsById(buildingUnitInput);
buildingApp.streetName = Request["buildingaddress"];
buildingApp.isInHoush = Convert.ToBoolean(Request["buildingOutput.isInHoush"]);
buildingApp.houshName = Request["HoushName"];
// buildingUnitApp.BuildingId = updateApplication.buildingId;
buildingUnitApp.ResidenceStatus = Request["residentstatus"];
// copy object getBuildingUnitInput to updateBuildingUnitInput
var updateBuildingUnitInput = new UpdateBuildingUnitsInput()
{
BuildingId = buildingUnitApp.BuildingId,
ResidentName = buildingUnitApp.ResidentName,
ResidenceStatus = buildingUnitApp.ResidenceStatus,
NumberOfFamilyMembers = buildingUnitApp.NumberOfFamilyMembers,
Floor = buildingUnitApp.Floor,
UnitContentsIds = buildingUnitApp.UnitContentsIds
};
//============================================
// copy object from getBuildingOutput to updateBuildingInput
var updateBuildingInput = new UpdateBuidlingsInput()
{
Id = buildingApp.Id,
buildingID = buildingApp.buildingID,
numOfBuildingUnits = buildingApp.numOfBuildingUnits,
numOfFloors = buildingApp.numOfFloors,
streetName = buildingApp.streetName,
buildingNo = buildingApp.buildingNo,
neighborhoodID = buildingApp.neighborhoodID,
buildingTypeID = buildingApp.buildingTypeID,
GISMAP = buildingApp.GISMAP,
houshProperty = buildingApp.houshProperty,
houshName = buildingApp.houshName,
X = buildingApp.X,
Y = buildingApp.Y,
buildingName = buildingApp.buildingName,
isInHoush = buildingApp.isInHoush,
buildingUsesID = buildingApp.buildingUsesID
};
//======================================================
updateApplication.Id = Convert.ToInt32(Request["applicationId"]);
updateApplication.fullName = model.fullName;
updateApplication.phoneNumber1 = model.phoneNumber1;
updateApplication.phoneNumber2 = model.phoneNumber2;
updateApplication.isThereFundingOrPreviousRestoration = model.isThereFundingOrPreviousRestoration;
updateApplication.isThereInterestedRepairingEntity = model.isThereInterestedRepairingEntity;
updateApplication.housingSince = model.housingSince;
updateApplication.previousRestorationSource = model.previousRestorationSource;
updateApplication.interestedRepairingEntityName = model.interestedRepairingEntityName;
updateApplication.PropertyOwnerShipId = Convert.ToInt32(Request["PropertyOwnerShip"]);
updateApplication.otherOwnershipType = model.otherOwnershipType;
updateApplication.interventionTypeId = Convert.ToInt32(Request["interventionTypeName"]);
updateApplication.otherRestorationType = model.otherRestorationType;
updateApplication.propertyStatusDescription = model.propertyStatusDescription;
updateApplication.requiredRestoration = model.requiredRestoration;
updateApplication.buildingId = Convert.ToInt32(Request["buildingnumber"]);
updateApplication.buildingUnitId = Convert.ToInt32(Request["dropDownBuildingUnitApp"]);
// ==== get of restoration types which it is multi select drop down list ======
var restorationTypes = Request["example-getting-started"];
string[] restorationTypesSplited = restorationTypes.Split(',');
byte[] restorationTypesArray = new byte[restorationTypesSplited.Length];
for (var i = 0; i < restorationTypesArray.Length; i++)
{
restorationTypesArray[i] = Convert.ToByte(restorationTypesSplited[i]);
}
updateApplication.restorationTypeIds = restorationTypesArray;
// ====== end of RestorationTypes
_buildingsAppService.update(updateBuildingInput);
_applicationsAppService.Update(updateApplication);
// _buildingUnitsAppService.Update(updateBuildingUnitInput);
// ==== get list of applications ==============
var applicationsUpdate = _applicationsAppService.getAllApplications();
var applicationsViewModel = new ApplicationsViewModel()
{
Applications = applicationsUpdate
};
return View("Applications", applicationsViewModel);
}
How ASP.NET Boilerplate template, which I use, makes CRUD Operation to database:
public class BuildingsManager : DomainService, IBuildingsManager
{
private readonly IRepository<Buildings> _repositoryBuildings;
public BuildingsManager(IRepository<Buildings> repositoryBuildings)
{
_repositoryBuildings = repositoryBuildings;
}
// create new building in table buildings .
public async Task<Buildings> create(Buildings entity)
{
var building = _repositoryBuildings.FirstOrDefault(x => x.Id == entity.Id);
if(building!=null)
{
throw new UserFriendlyException("Building is already exist");
}
else
{
return await _repositoryBuildings.InsertAsync(entity);
}
}
// delete a building from buildings table .
public void delete(int id)
{
try
{
var building = _repositoryBuildings.Get(id);
_repositoryBuildings.Delete(building);
}
catch (Exception)
{
throw new UserFriendlyException("Building is not exist");
}
}
public IEnumerable<Buildings> getAllList()
{
return _repositoryBuildings.GetAllIncluding(b => b.BuildingType, n => n.NeighboorHood,u=>u.BuildingUses);
}
public Buildings getBuildingsById(int id)
{
return _repositoryBuildings.Get(id);
}
public void update(Buildings entity)
{
_repositoryBuildings.Update(entity);
}
}
How can I solve this problem? Many thanks for help.
By creating a new entity (updateBuildingInput) with the same primary key as one you have already read in your context, Entity will throw an error when you attempt an operation on the new entity (as you have seen) as it is already tracking an entity with that primary key in the context.
If _buildingsAppService is a DbContext and all you need to do is make some changes to an entity, you can:
Read the entity
Make changes directly to that entity object
Call _buildingsAppService.SaveChanges()
SaveChanges() will:
Saves all changes made in this context to the underlying database.
When getting the record from db you can use .AsNoTracking()
Or if you really need to update an attached entity first locate the attached copy and detach it, then modify and update;
public async Task<bool> UpdateAsync<T>(T entity)
where T : class, IHasId
{
// check if entity is being tracked
var local = _context.Set<T>().Local.FirstOrDefault(x => x.Id.Equals(entity.Id));
// if entity is tracked detach it from context
if (local != null)
_context.Entry<T>(local).State = EntityState.Detached;
_context.Attach(entity).State = EntityState.Modified;
var result = await _context.SaveChangesAsync();
// detach entity if it was not tracked, otherwise it will be kept tracking
if(local == null)
_context.Entry(entity).State = EntityState.Detached;
return result > 0;
}
btw, IHasId is a simple interface to make Id property accessible for generic types;
public interface IHasId {
int Id { get; set; }
}
Use .AsNoTracking():
public class BuildingsManager : DomainService, IBuildingsManager
{
public Buildings getBuildingsById(int id)
{
return _repositoryBuildings.GetAll().AsNoTracking().First(b => b.Id == id);
}
// ...
}

SQL Exception violation of primary key constraint when updating data

private void FormRentBook_Load(object sender, EventArgs e)
{
librarydb sorgu = new library();
var book = from booklist in query.k_Books
join isrent in query.k_Bookstatus
on booklist.Book_statusId equals isrent.k_typeid
join booktype in query.k_BookType
on booklist.book_type equals booktype.ID
select new
{
booklist.Book_Name,
booklist.Book_Author,
booktype.Book_type,
booklist.Book_Page,
booklist.ID,
isrent.k_typecomment,
};
bookscreen.DataSource = book.ToList();
bookscreen.Columns[0].HeaderText = "Book Name";
bookscreen.Columns[1].HeaderText = "bookscreen Author";
bookscreen.Columns[2].HeaderText = "Book Type";
bookscreen.Columns[3].HeaderText = "Page Number";
bookscreen.Columns[4].Visible = false;
bookscreen.Columns[5].HeaderText = "Book Status";
bookscreen.Show();
label6.Text = DateTime.Now.ToString();
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
}
public int a;
private void bookscreen_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
label1.Text = bookscreen.CurrentRow.Cells[0].Value.ToString();
label2.Text = bookscreen.CurrentRow.Cells[1].Value.ToString();
a =int.Parse( bookscreen.CurrentRow.Cells[4].Value.ToString());
label3.Text = bookscreen.CurrentRow.Cells[5].Value.ToString();
}
k_Rentedbooks rent = new k_Rentedbooks();
rent.renter_id = Login.k_id;
rent.renter_id = int.Parse(bookscreen.CurrentRow.Cells[4].Value.ToString());
rent.rent_date = DateTime.Now;
DateTime return = DateTime.Now;
int day;
day = Convert.ToInt32(comboBox1.SelectedItem.ToString());
rent.returndate = return.AddDays(day);
db.k_Rentedbooks.Add(rent);
var updatebook = db.k_Books.Where(w => w.ID ==a).FirstOrDefault();
updatebook.Kitap_statusId = 2;
db.SaveChanges();
i need to add data to k_KiralananKitaplar and update a row named Kitap_DurumId = 2 but i can only add data or update i cant do in one time db.SaveChanges give me error
Here's a sample of the data:
Kitap_Adi = book name,
Kitap_Yazar = book_author,
Kitap_Tur = book type,
Kitap_Sayfa = book page,
Kitap_DurumId = book status
The error message is
SqlException: Violation of PRIMARY KEY constraint 'PK_k_KiralananKitaplar'. Cannot insert duplicate key in object 'dbo.k_KiralananKitaplar'. The duplicate key value is (0).
In your update statement:
var updatebook = db.k_Books.Where(w => w.ID ==a).FirstOrDefault();
updatebook.Kitap_statusId = 2;
db.SaveChanges();
You're selecting a record where Id == a using FirstOrDefault and given that EntityFramework can't update this record, I'm going to assume that no record exists where Id == a so you need to handle a null return value from your query:
var updatebook = db.k_Books.FirstOrDefault(w => w.ID == a);
if (updatebook != null)
{
updatebook.Kitap_statusId = 2;
db.SaveChanges();
}
In this case, if a record was returned by the query, it'll update Kitap_statusId, otherwise, it won't do anything.
Update
Per OP comment on this question:
i solved problem but now i need to find when i insert new data in a table other table insert to same table to how can i do that
You just need to get the Id values of the newly insert entity and use that to insert a record into the 2nd table.
So in your code you have the first item being inserted:
db.k_Rentedbooks.Add(rent);
When you do the SaveChanges() for this, it'll automatically update the entity with its new Id, so lower down in that function you can then add a new record to the 2nd table using the Id value for rent.
As a rough example:
var Book = new Book{ statusId = rent.Id };
db.SecondTable.Add(Book);
db.SaveChanges();

Categories