DbUpdateException Whiles updating record using LINQ to Database - c#

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.

Related

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint The conflict occurred in database table column

i want save record the id_ats and id_ex from another table, but i always get error foreign key constraint. please help me..
Controller :
[HttpPost]
public ActionResult SaveRecord(IEnumerable<exercises> model)
{
foreach (var item in model)
{
ex_op dbitem = new ex_op();
if (db.ex_op.Any(x => x.id_test == item.Id))
{
dbitem = db.ex_op.Where(x => x.id_test == item.Id).FirstOrDefault();
dbitem.id_test = item.Id;
dbitem.id_ats = item.IdAts;
dbitem.id_ex = item.IdExercises;
dbitem.start_test = item.StartTest;
dbitem.end_test = item.EndTest;
dbitem.best_time = item.BestTime;
dbitem.performance = item.performance;
dbitem.status = item.status;
dbitem.comment = item.comment;
db.Entry(dbitem).State = EntityState.Modified;
}
else
{
dbitem.id_test = item.Id;
dbitem.id_ats = item.IdAts;
dbitem.id_ex = item.IdExercises;
dbitem.start_test = item.StartTest;
dbitem.end_test = item.EndTest;
dbitem.best_time = item.BestTime;
dbitem.performance = item.performance;
dbitem.status = item.status;
dbitem.comment = item.comment;
db.ex_op.Add(dbitem);
}
db.SaveChanges();
}
return RedirectToAction("Index", new { msg = "Sukses" });
}
Usually with foreign key constraint errors the problem is that the ID you are using to update or insert does not exist in the related table.
E.g. if a box(BoxTable) has apples(AppleTable) and the apple table has a foreign key pointing to box table then a box must exist for an apple to be created or inserted.
If the you use an id that does not exist in the box table then you get a foreign key constraint error.

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();

C# Linq with four tables and one foreign key that isn´t always needed

I have the problem that I have a MariaDB database with HeidiSQL. There are four tables and im using Linq to insert new data. One of the tables isn´t always necessary. So i marked the column with the foreign key in one of the a other tables for can be NULL. The problem is that when i create the new objects to insert into database it creates the new data in the database but the foreign key in the other table keeps emtpy.
When i undo the Null option in the column and want to insert a standardvalue instead, it throws an UpdateEntityException.
What i should mention is, that i cerated the database first in HeidiSQL and created then the code in Visual Studio with EntityFramework 5.0.
Or might the mistake caused by building and adding the database object in an if-clause?
There are some code examples of my code, i hope it will help.
DateTime aktuellesDatum = DateTime.Now;
int proId = getProjectIdByProjectnumber(zeichnungen[0].Projektnummer);
int tagId = getTagIdByTag(zeichnungen[0].Tag, zeichnungen[0].Projektnummer);
string hauptzeichnung = "";
int gruppeId = -1;
//Noch kein Projekt vorhanden
if(proId == -1)
{
using (DMSContext db = new DMSContext())
{
foreach (ZeichnungInDB zeichnungInDB in zeichnungen)
{
zeichnungInDB.Volante_Index = getVolCountByDrawingNumber(zeichnungInDB.Zeichnungsnummer) + 1;
var zeichnung = new zeichnung()
{
Zeichnung_ID = zeichnungInDB.Dateiname + "_" + zeichnungInDB.Index + "_VOL_" + zeichnungInDB.Volante_Index + "_" + aktuellesDatum.ToShortDateString(),
Zeichnungsnummer = zeichnungInDB.Zeichnungsnummer,
Index = zeichnungInDB.Index,
Zeitstempel = aktuellesDatum,
Dateiname_Org = zeichnungInDB.Dateiname,
Aenderung_Ext = zeichnungInDB.Aenderung_Ext,
Aenderung_Int = "AE_" + zeichnungInDB.Projektnummer + "_" + aktuellesDatum.Year + "-" + aktuellesDatum.Month + "-" + aktuellesDatum.Day + " " + aktuellesDatum.Hour + ":" + aktuellesDatum.Minute,
Dokumententyp = zeichnungInDB.DokumentenTyp,
Dateiendung = zeichnungInDB.Extension,
Volante_Index = zeichnungInDB.Volante_Index,
MMS_Sachmerkmal = zeichnungInDB.Mms_Sachmerkmal,
Status = zeichnungInDB.Status,
Aenderung_Bemerkung_Txt = zeichnungInDB.Aenderung_Bemerkung_Text,
Einzel_Bemerkung_Txt = zeichnungInDB.Einzel_Bemerkung,
Ahang_Link = zeichnungInDB.Anhang_Link,
Einzel_Link = zeichnungInDB.Einzel_Link,
};
db.zeichnungs.Add(zeichnung);
if(zeichnungInDB.Baugruppe_Hauptzeichnung == true)
{
hauptzeichnung = zeichnungInDB.Zeichnungsnummer;
}
}
var projekt = new projekt()
{
Projektnummer = zeichnungen[0].Projektnummer,
};
var tag = new tag()
{
Tag1 = zeichnungen[0].Tag,
};
if (!hauptzeichnung.Equals(""))
{
var baugruppe = new baugruppe
{
Hauptzeichnung = hauptzeichnung,
};
db.baugruppes.Add(baugruppe);
}
db.projekts.Add(projekt);
db.tags.Add(tag);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
// raise a new exception nesting
// the current instance as InnerException
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
}
This is only a short e.g. from my code because the whole cs would be to long and nobody would spend the time on so much code.
One other thing i would like to ask is. If the following code works correct for update a string in a field?
private static void updateHauptzeichnung(int baugruppeId, string zeichnungsnummer)
{
using (var context = new DMSContext())
{
var query = context.baugruppes
.Where(b => b.Baugruppe_ID == baugruppeId)
.Select(g => new { g.Hauptzeichnung })
.SingleOrDefault();
if (query != null)
{
query.Hauptzeichnung.Replace(query.Hauptzeichnung, zeichnungsnummer);
}
context.SaveChanges();
}
}
I solved my problem. I changed the foreignkey field from can be NULL to is necessary, added in the foreign table a costum dataset with ID is 0 and I give new data this ID as its foreign ID when they have no offical link to the foreign table. It might not be the best solution, but it fixed my problem.

entity framework add data to table

I'm trying to insert data into a MariaDB with EntityFrameWork 5 in Visual Studio. I created the database on the server itself and imported the model in Visual Studio. I'm using three tables and they are linked.
A draing table, project table and tag table.
Entities are: drawing (many---1) project (1---many) tag.
For the insert I use the code below. But it throws an DbUpdateEntityException who tells that he can't match the key between the drawing and project table because two or more primary keys are the same. I use a specific primary key for dat drawing which is definitely not the same with a other object in the table. The other primary keys are AUTO_INCREMENT So I guess that it tries to insert a new project but with the same project number which don't work but I don't really get it why it is doing this.
DateTime aktuellesDatum = DateTime.Now;
using (DMSContext db = new DMSContext())
{
foreach (ZeichnungInDB zeichnungInDB in zeichnungen)
{
zeichnungInDB.Volante_Index = getVolCountByDrawingNumber(zeichnungInDB.Zeichnungsnummer) + 1;
var zeichnung = new zeichnung()
{
Zeichnung_ID = zeichnungInDB.Dateiname + "_" + zeichnungInDB.Index + "_VOL_" + zeichnungInDB.Volante_Index + "_" + aktuellesDatum.ToShortDateString(),
Baugruppe = zeichnungInDB.Baugruppe,
Baugruppe_Hauptzeichnung = zeichnungInDB.Baugruppe_Hauptzeichnung,
Zeichnungsnummer = zeichnungInDB.Zeichnungsnummer,
Index = zeichnungInDB.Index,
Dateiname_Org = zeichnungInDB.Dateiname,
Aenderung_Ext = zeichnungInDB.Aenderung_Ext,
Aenderung_Int = "AE_" + zeichnungInDB.Projektnummer + aktuellesDatum,
Dokumententyp = zeichnungInDB.DokumentenTyp,
Dateiendung = zeichnungInDB.Extension,
Volante_Index = zeichnungInDB.Volante_Index,
MMS_Sachmerkmal = zeichnungInDB.Mms_Sachmerkmal,
Status = zeichnungInDB.Status,
Aenderung_Bemerkung_Txt = zeichnungInDB.Aenderung_Bemerkung_Text,
Einzel_Bemerkung_Txt = zeichnungInDB.Einzel_Bemerkung,
Ahang_Link = zeichnungInDB.Anhang_Link,
Einzel_Link = zeichnungInDB.Einzel_Link,
};
var projekt = new projekt()
{
Projektnummer = zeichnungInDB.Projektnummer,
};
var tag = new tag()
{
Tag1 = zeichnungInDB.Tag,
};
db.zeichnungs.Add(zeichnung);
db.projekts.Add(projekt);
db.tags.Add(tag);
}
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
// raise a new exception nesting
// the current instance as InnerException
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
}
maybe someone has an idea or a solution where the problem is.
(The "ZeichnungInDB" is an custom object and "zeichnungen" is ObservableCollection)
The other question I have is, I implemented a field for date time which is CURRENT_TIMESTSAMP but it only shows 0000-00-00 00:00:00 why is this?
Are you using fluent API? if you are, you should mark the id's properties as Identity like the example:
Property(p => p.DrawingId).
HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Or you can mark with an annotation in the primary key of your entities like the example:
public class drawing {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ind DrawingId {get; set;}
....
}
link:
http://www.opten.ch/blog/2014/03/5/configuring-entity-framework-with-fluent-api/
regards.

FOREIGN_KEY constraint exception

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();

Categories