i am getting "The object cannot be deleted because it was not found in the ObjectStateManager". while Deleting object.
here is codes ;
//first i am filling listview control.
private void Form1_Load(object sender, EventArgs e)
{
FirebirdEntity asa = new FirebirdEntity();
ObjectQuery<NEW_TABLE> sorgu = asa.NEW_TABLE;
foreach (var item in sorgu)
{
ListViewItem list = new ListViewItem();
list.Text = item.AD;
list.SubItems.Add(item.SOYAD);
list.Tag = item;
listView1.Items.Add(list);
}
//than getting New_table entity from listview's tag property.
private void button3_Click(object sender, EventArgs e)
{
using (FirebirdEntity arama = new FirebirdEntity())
{
NEW_TABLE del = (NEW_TABLE)listView1.SelectedItems[0].Tag;
arama.DeleteObject(del);
arama.SaveChanges();
}}
Delete a Record In Connected Scenario, you can use the Remove or RemoveRange method to mark the record as Deleted . In Disconnected Scenario, you can attach it to the context and set its state as Deleted . Calling SaveChanges will send the delete query to the database.
Cascade delete automatically deletes dependent records or sets null to ForeignKey columns when the parent record is deleted in the database. Cascade delete is enabled by default in Entity Framework for all types of relationships such as one-to-one, one-to-many and many-to-many.
Entity Framework Core Cascade Delete The OnDelete method takes a DeleteBehavior enum as a parameter: Cascade: Child/dependent entity should be deleted. Restrict: Dependents are unaffected. SetNull: The foreign key values in dependent rows should update to NULL.
You need to attach the object to the ObjectContext
. Try:
NEW_TABLE del = (NEW_TABLE)listView1.SelectedItems[0].Tag;
arama.Attach(del);
arama.DeleteObject(del);
arama.SaveChanges();
Attached objects are tracked by the ObjectContext
. This is needed for performing deletes and updates. You can read more about attaching objects on MSDN.
Edit to clarify attach/detach:
private void Form1_Load(object sender, EventArgs e) {
FirebirdEntity asa = new FirebirdEntity();
ObjectQuery<NEW_TABLE> sorgu = asa.NEW_TABLE;
foreach (var item in sorgu) {
asa.Detach(item);
// add to listView1
}
}
Also, you should wrap your use of ObjectContext
s in using
blocks.
In your method "Form1_Load" you create a FIRST instance of your "FirebirdEntity" context an fill the ListViewItem with entities selected from this context
In your method "button3_Click" you create a NEW, SECOND instance of your "FirebirdEntity" context. Then you try to delete an entity in this SECOND context, which was selected in the FIRST context.
Use the same instance of your context in both of your methods and everything will work fine.
(Alternatively you can select the entity you want to delete a from your SECOND context and then delete this entity instead of the origin one)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With