Reputation: 9332
I have a DeleteUser function with a bool return value. My ORM is Entity Framework. As you can see below, I force the true value at the end of the function which is not quite pretty well. How can I proceed to place this return (bool) value only when the SaveChanges do his job (deleting the user)? Maybe a try...catch? Another solution?
public bool DeleteUser(string username)
{
User user = m_context.Users.Where(u => u.UserName == username).FirstOrDefault();
m_context.Users.Remove(user);
m_context.SaveChanges();
return true;
}
Thanks.
Upvotes: 0
Views: 382
Reputation: 8631
I don't know if this is the best approach but you can confirm the deleted user doing this:
public bool DeleteUser(string username)
{
User user = m_context.Users.Where(u => u.UserName == username).FirstOrDefault();
m_context.Users.Remove(user);
m_context.SaveChanges();
User deletedUser = m_context.Users.Where(u => u.UserName == username).FirstOrDefault();
if (deletedUser == null)
return true;
return false;
}
Upvotes: 1
Reputation: 35533
try...catch should work:
public bool DeleteUser(string username)
{
try
{
User user = m_context.Users.Where(u => u.UserName == username).FirstOrDefault();
m_context.Users.Remove(user);
m_context.SaveChanges();
}
catch(Exception ex)
{
return false;
}
return true;
}
Returning a boolean won't give you the reason for the exception, however.
Upvotes: 0