I'm using Entity Framework 6 with Code First on an SQL server. Today, with my greatest surprise, I received an exception Sequence contains more than one element
on a a simple query by ID (in my domain, the primary Key of each object). After debugging, I found that in my database 2 identical entities with the same Primary Key exist.
Now, I have no idea how that could happen, but my biggest problem right now is how to solve the issue: I cannot just delete them both, since they are 2 users with important data associated to them. So I tried to remove just one, but I receive an exception due to the fact that some other object references this user (and again, I cannot delete those objects because they contain important data).
var users = _userService.GetAllBy().ToList();
var duplicatedUsers = users.Where(x => users.Count(y => y.Id == x.Id) > 1);
foreach (var user in duplicatedUsers)
{
try
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
catch (Exception e)
{
// it always enters here because of the foreign keys
}
}
Basically, since the 2 identical objects have the same foreign key, they also share the same relationships with the other related entities. Therefore, I cannot just simply delete one of them because that causes an exception. But I don't want to delete them both either, because that would cause data loss. Any suggestion?