Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting Entity Object with 1 to Many Association to View-Based Entity

I have a Model-First entity model which contains a Customer table linked to a view that fetches customer details from a separate database. The relationship is One to Many between the Customer table and the View and I have a navigation property on both the Customer entity and the View entity.

When I try to perform a delete using context.Customers.DeleteObject(cust) and call context.SaveChanges() I get an error:

Unable to update the EntitySet 'ViewEntity' because it has a DefiningQuery and no [DeleteFunction] element exists element to support the current operation.


I have tried setting On Delete Cascade and None and both generate the same error.

EDIT: There's not much code to show, but here you go:

Customer selectedCust = (Customer)dgvCustomers.SelectedRows[0].DataBoundItem;
if (selectedCust != null)
{
    if (MessageBox.Show(String.Format("Are you sure you want to delete Customer {0}?", selectedCust.CustomerID.ToString()), 
                            "Customer Delete Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        // TODO - Fix this
        this.ReportSchedDBContext.Customers.DeleteObject(selectedCust);
        this.ReportSchedDBContext.SaveChanges();                      
    }
}
like image 896
Overhed Avatar asked Apr 22 '16 00:04

Overhed


2 Answers

Many related posts in SO agree with @Overmachine... you are probably missing a primary key on your entity/table.

See..

because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element

and

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist


EDIT

Just saw your comment regarding your Customer table having a primary key but your view not. Not sure whats going on without more of your code, but ultimately all you need is a Customer object with the primary key(s) set on it, then you can use the following code to delete a detached entity object.

this.ReportSchedDBContext.Entry(selectedCust).State = EntityState.Deleted;
this.ReportSchedDBContext.SaveChanges();  

If you are casting from another type and that is causing problems, you could also do:

var cust = new Customer { CustomerID = selectedCust.CustomerID };
this.ReportSchedDBContext.Entry(cust).State = EntityState.Deleted;
this.ReportSchedDBContext.SaveChanges();  
like image 94
Chris Curtis Avatar answered Oct 21 '22 04:10

Chris Curtis


I was able to work around this issue by creating a dummy Stored Procedure that does nothing ("SELECT 'Done'") and using the SP Function Mapping in my two Views to set the Delete function to this Stored Procedure. Quite a hack but it worked.

I'm not sure why a Delete Function is required for a View or if I'm doing something else wrong which caused the issue, but the above worked for me.

like image 20
Overhed Avatar answered Oct 21 '22 04:10

Overhed