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();
Related
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.
I have two tables named Order and Invoice_Line_Items. I have a column called "invoice_number" in both tables "invoice_number" and Invoice_Line_Items. But "invoice_number" column in Invoice_Line_Items table is empty. I need to copy the data present in the "invoice_number" column from the Order table to "invoice_number" column in Invoice_Line_Items table.
This is an example of what I want to achieve
Looks like the relationship between these 2 tables are Order_id?
This is just the example:
var query = from it in db.Invoice_Line_Items
join order in db.Order
on it.Order_id equals order.Order_id into lg
from order in lg.DefaultIfEmpty()
select new Invoice_Line_Items
{
Order_id = it.Order_id,
Invoice_number = order == null? null: order.Invoice_number,
item = it.item,
quantity = it.quantity
};
I managed to solve the issue and here is the code below
changed the table name from order to ordering
the invoice_number from Invoice_Line_Items made it retrieve the maximum number from ordering table order_id
public ActionResult SaveOrder(Order[] requesting)
{
string result = "Error! Order Is Not Complete!";
using (mymodel dbb = new mymodel())
{
var customerId = Guid.NewGuid();
Ordering ord = new Ordering();
ord.CustomerId = customerId;
ord.date_order_placed = DateTime.Now;
dbb.Orderings.Add(ord);
if (dbb.SaveChanges() > 0)
{
string order_id = dbb.Orderings.Max(o => o.invoice_number);
foreach(var item in requesting)
{
Invoice_Line_Items in_l_i = new Invoice_Line_Items();
in_l_i.invoice_number = order_id;
in_l_i.department = item.depart;
in_l_i.service = item.Service;
in_l_i.gender = item.Gender;
in_l_i.item = item.Item;
in_l_i.quantity = item.Quantity;
in_l_i.price = item.price;
dbb.Invoice_Line_Items.Add(in_l_i);
}
if (dbb.SaveChanges() > 0)
{
result = "Success! Order Is Complete!";
}
}
}
return Json(result, JsonRequestBehavior.AllowGet);
}
I have a database that contains 'Personne' table, 'Patient' table (this one contains a foreign key to the id of 'Personne'), and 'RendezVous' table. i want to add a new element on my RendezVous table, but in my 'RendezVous' table i want the idPatient, and i am entering the first and last name in my app so i have to do a search on 'Personne' table to get the idPerson, and search that id on my 'Patient' table to get it the idPatient. If the patient doesn't exist, i put the id on 1. I'm using LinQ to SQL, but it doesn't work... Can i get some help?
public void AddRdv(DateTime date, byte idMedecin, string nomPatient, string prenomPatient, bool important, string notes)
{
string con = $#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)}\MCDatabase.mdf;Integrated Security=True";
MCDataClassDataContext dataClass = new MCDataClassDataContext(con);
var patientRdv = (from personne in dataClass.Personne
where nomPatient == personne.nom && prenomPatient == personne.prenom
join patient in dataClass.Patient on personne.Id equals patient.IdPersonne
select personne);
Personne pers=patientRdv.First();
if (patientRdv.Count()!=0)
{
pers = patientRdv.First();
RendezVous rdv = new RendezVous
{
Date = date,
IdPatient = pers.Id,
IdMedecin = idMedecin,
Important = important,
Fait = false,
Note = notes
};
dataClass.RendezVous.InsertOnSubmit(rdv);
dataClass.SubmitChanges();
}
else
{
RendezVous rdv = new RendezVous
{
Date = date,
IdPatient = 1,
IdMedecin = idMedecin,
Important = important,
Fait = false,
Note = notes
};
dataClass.RendezVous.InsertOnSubmit(rdv);
dataClass.SubmitChanges();
}
}
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();
I'm trying to insert some data in my database using Entity Framework model, but for some unknown reasons to me, it does nothing.
Am I missing something here?
using (var context = new DatabaseEntities())
{
var t = new test
{
ID = Guid.NewGuid(),
name = "blah",
};
context.AddTotest(t);
context.SaveChanges();
}
It should be:
context.TableName.Add(TableEntityInstance);
For versions of entity framework before 6, it was:
context.TableName.AddObject(TableEntityInstance);
Where:
TableName: the name of the table in the database.
TableEntityInstance: an instance of the table entity class.
If your table is Orders, then:
Order order = new Order();
context.Orders.Add(order);
For example:
var id = Guid.NewGuid();
// insert
using (var db = new EfContext("name=EfSample"))
{
var customers = db.Set<Customer>();
customers.Add( new Customer { CustomerId = id, Name = "John Doe" } );
db.SaveChanges();
}
Here is an example:
public void UpdatePlayerScreen(byte[] imageBytes, string installationKey)
{
var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault();
var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault();
if (current != null)
{
current.Screen = imageBytes;
current.Refreshed = DateTime.Now;
this.ObjectContext.SaveChanges();
}
else
{
Screenshot screenshot = new Screenshot();
screenshot.ID = Guid.NewGuid();
screenshot.Interval = 1000;
screenshot.IsTurnedOn = true;
screenshot.PlayerID = player.ID;
screenshot.Refreshed = DateTime.Now;
screenshot.Screen = imageBytes;
this.ObjectContext.Screenshots.Add(screenshot);
this.ObjectContext.SaveChanges();
}
}
var context = new DatabaseEntities();
var t = new test //Make sure you have a table called test in DB
{
ID = Guid.NewGuid(),
name = "blah",
};
context.test.Add(t);
context.SaveChanges();
Should do it
[HttpPost] // it use when you write logic on button click event
public ActionResult DemoInsert(EmployeeModel emp)
{
Employee emptbl = new Employee(); // make object of table
emptbl.EmpName = emp.EmpName;
emptbl.EmpAddress = emp.EmpAddress; // add if any field you want insert
dbc.Employees.Add(emptbl); // pass the table object
dbc.SaveChanges();
return View();
}