开发者

Deleting objects in the right order with EF

开发者 https://www.devze.com 2023-04-12 11:06 出处:网络
I have two classes created by Entity Framework based off tables in my db public class AttributeDefinition

I have two classes created by Entity Framework based off tables in my db

public class AttributeDefinition
{
    int id { get; set; }
    string Type { get; set; }
    string Description { get; set; }
    EntityCollection<AttributeValue> AttributeValues { get; set; }
}

public class AttributeValue
{
    int id { get; set; }
    string Value { get; set; }
    AttributeDefinition AttributeDefinition { get; set; }
}

In the database, the relationship is开发者_高级运维 specified by a foreign key column AttributeDefinitionID in the AttributeValue table.

The case where I want to delete is the following:

if (definition.AttributeValues.Count == 1)
    _db.AttributeValues.DeleteObject(definition.AttributeValues.First());
/*
else if (definition.AttributeValues.Count == 0)
    nothing needs to be done
else if (definition.AttributeValues.Count > 1)
    allow delete of AttributeDefinition, constraint will throw error on save
    which is caught and handled to output error
*/

_db.AttributeDefinitions.DeleteObject(definition);
_db.SaveChanges();

I thought this should work, however it seems to be attempting to delete the AttributeDefinition first, so I get a reference constraint error:

The DELETE statement conflicted with the REFERENCE constraint "FKAttributeV644147". The conflict occurred in database "Test", table "dbo.AttributeValue", column 'AttributeDefinitionID'. The statement has been terminated.

If I save between deletes it works fine:

if (definition.AttributeValues.Count == 1)
{
    _db.AttributeValues.DeleteObject(definition.AttributeValues.First());
    _db.SaveChanges();  //Save between deletes
}

_db.AttributeDefinitions.DeleteObject(definition);
_db.SaveChanges();

I DON'T want to use cascade deletes as if there is more than one attribute value assigned to this attribute definition, I want the constraint to throw an exception to say that this can't be deleted.

Any ideas?


So this may be a special case but I figured I would add the answer just in case people were interested or were looking for it.

As it turns out, EF hadn't imported the referential constraint from the DB when updating the model. I worked this out by looking under Constraints in the Model Browser. This led to it not knowing the order to delete entities in when saving to the database.

Once I had worked that out, I knew from previous experience that if you put a non-clustered index on a primary key that is used in the constraint, EF has a hissy fit and doesn't import it. See here for details.

So I simply dropped the index, reimported the constraint, and now it all works as it should.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号