Bill Greer
Bill Greer

Reputation: 3156

Unique Key Constraint Check In Entity Framework

I have a unique key constraint in my SQL Server that is based on two columns (AbsoluteCounter, TimeMfrAudit). If I try to add a list of objects via Entity Framework, how can I check if one of my objects is going to violate this constraint without throwing an exception that will make my entire context.SaveChanges() fail ? I am looking for a best practice here.

Thanks

Upvotes: 3

Views: 589

Answers (1)

Slauma
Slauma

Reputation: 177133

These would be all objects that violate the unique key constraint:

var violatingObjects = listOfObjectsToAdd
    .Where(o => context.Objects.Any(oInDb =>
        oInDb.AbsoluteCounter == o.AbsoluteCounter &&
        oInDb.TimeMfrAudit == o.TimeMfrAudit))
    .ToList();

It is one EXISTS database query per object in the list. If you only want to know the first object that violates the constraint use FirstOrDefault() instead of ToList(). If you only want to know if there is any violating object at all use Any() instead of ToList(). The iteration should stop when the first object has been found.

Upvotes: 1

Related Questions