简体   繁体   中英

C# Delete row from multiple tables

Situation: I have 3 tables:

  • movies ( pk:movietitle, movielength ....etc)
  • rentals ( pk:personid, fk:movietitle, ...etc)
  • rentingpeople ( pk+fk:personid, name, phone ...etc)

On my form there is a listbox bindingsourced with the movie titles, next to the listbox there are textboxes bindingsourced from db.movies

When someone click on the rentthismovie button I would like to delete the current rental data about that movie from table rentals and rentingpeople .

I wrote the first part and get an error because of foreign keys problem (I mentioned primary key as pk and foreign key as fk in the tables above)

var search = (from g in db.Rentals 
              where g.Movietitle == (string)listBox1.SelectedValue select g).First();

db.Rentals.DeleteObject(search);
db.SaveChanges();

I get an error:

The DELETE statement conflicted with the REFERENCE constraint \\"FK_Rentingpeople_Rentals\\". The conflict occurred in database \\"C:\\USERS\\PC\\DOCUMENTS\\VISUAL STUDIO 2010\\PROJECTS\\FILMEK\\FILMEK\\BIN\\DEBUG\\DATABASE1.MDF\\", table \\"dbo.Rentingpeople\\", column 'personid'.\\r\\nThe statement has been terminated.

Because of the primary-foreign key connection I must delete the data from rentingpeople table too as I read from this error but I can't really find a working solution.

The problem is in the db design

movies(pk:movietitle,movielength....etc)
rentals(pk:personid,fk:movietitle,...etc)
rentingpeople(pk+fk:personid,name,phone...etc)

If I got this right, movies contains the list of movies, rentingpeople is the list of people who are renting or have rented, and rentals tracks rentals. If so, rentingpeople.personid should be a pk, and rentals.personid should be an fk to the other, like this:

  • movies(pk:movietitle,movielength....etc)
  • rentals(fk:personid,fk:movietitle,...etc)
  • rentingpeople(pk:personid,name,phone...etc)

if you want to improve search on rentals (assuming any one person can exercise multiple rentals at the same time) you can introduce a non-unique index on personid, or a composite unique index to personid and movietitle on table rentals

You need to delete all the PK and not null references to the object you are deleting before you delete object itself.
You can change non nullable columns to nullable ones if logic allows.

var rentalsToBeDeleted = db.Rentals.Where(o =>o.movieid == movieid).ToList();
for (int i = rentalsToBeDeleted.count; i < 0; i--)
{
 db.Rentals.DeleteObject(rentalsToBeDeleted.elementAt(i));
}

after all the referenced deleted.

db.SaveChanges();

writing without VS so mistakes are likely but you should get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM