toby toby - 3 months ago 29
ASP.NET (C#) Question

Store update, insert, or delete statement affected an unexpected number of rows (0) EntityFramework

I keep getting the fallowing error when i try to save changes made to a context


Store update, insert, or delete statement affected an unexpected
number of rows (0). Entities may have been modified or deleted since
entities were loaded. Refresh ObjectStateManager entries.


I have the fallowing classes.
Person

public class Person : IPerson
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string FirstName { get; set; }

public string LastName { get; set; }

public string Name
{
get
{
return FirstName + " " + LastName;
}
set{}
}

public string Email { get; set; }
public DateTime? LastModified { get; set; }
public virtual ICollection<Result> Results { get; set; }
}


UserProfile

public class UserProfile : Person
{
public UserProfile()
{
Faculty = new Faculty();
Projects = new Collection<Project>();
Results = new Collection<Result>();
}
public string UserName { get; set; }
public string CNP { get; set; }
public virtual Faculty Faculty { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}


Result

public abstract class Result:INamedEntity
{
protected Result()
{
ResultType = new ResultType();
}
public int Id { get; set; }
public string Name{get;set;}
public virtual ResultType ResultType { get; set; }
public virtual ICollection<Person> People { get; set; }
public DateTime? LastModified { get; set; }
}


After i add a value to the context using

_ctx.Users.Single(u => u.Id == userId).Results.Add(result);


I get the error when i call
_ctx.SaveChanges()


Updated my function to

public bool Save()
{

try
{
_ctx.SaveChanges();
}
catch (OptimisticConcurrencyException)
{
((IObjectContextAdapter)_ctx).ObjectContext.Refresh(RefreshMode.ClientWins,_ctx.Users);
((IObjectContextAdapter)_ctx).ObjectContext.Refresh(RefreshMode.ClientWins,_ctx.Results);
_ctx.SaveChanges();
}
return true;
}


But the error isn't caught.
Thank you

Answer

Figured it out. The problem was that there's two of us working on this project, and my colleague created his own instance of DBContext he was updating one and i the other. So for who ever has this problem in the future make sure you don't have two different instances of your DBContext at the same time