简体   繁体   中英

Deleting an Entity Framework object that may or may not already exist in the database

I'm using the Entity Framework 6, database first (I'm new to EF). I have two entity classes, Structure and Contour , where a Structure may contain multiple objects of type Contour . I would like to be able to remove Contours whether or not they already exist in the database. For example, if I add a new Contour to an existing Structure object like this:

Contour contour = new Contour
{
    Structure = structure,
};

I can delete it like this:

contour.Structure = null;

But if the contour already exists in the database and I delete it, saving the entity context throws the exception "The relationship could not be changed because one or more of the foreign-key properties is non-nullable..."

That exception tells me that the entity context wasn't aware that it's supposed to delete that Contour . My fix was to delete a Contour as follows:

contour.Structure = null;
EntityContext.Contours.Remove(contour);

But if the contour doesn't exist in the database already (because it was just added), then the entity context is not aware of it and it doesn't find it in its Contours list. So then I modified my delete method to this:

contour.Structure = null;
if (EntityContext.Contours.Local.Contains(contour))
{
    EntityContext.Contours.Remove(contour);
}

This appears to work so far, but is this how I'm supposed to delete entity objects that may or may not already exist in the database?

Don't make it too complex, you may remove contour by simple call context.Contours.Remove(contour) . It doesn't care is contour already in database or not. For example:

using (var context = new EntityContext())
{
    Vendor vendor = new Vendor();
    context.Vendors.Add(vendor);
    context.Vendors.Remove(vendor);
    context.SaveChanges();
}

Two options:

dbContext.Contours.Remove( contour );

or

structureInstance.Contours.Remove( contour ); // but this will load all of a structure's contours if not loaded already

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