BraveHeart BraveHeart - 3 months ago 7
C# Question

What is the best practice for updating or adding records to the Database?

Lets say I have a DatabaseService class that has Update(user) and Add(user).
My question is about having them both in one method. Is it a good practice or not ?
For example if i have a mothed like this

public void AddOrUpdateUser(User user)
{
var userFound = GetUserById(user.Id);
if (userFound == null)
{
AddUser(user);
}
else
{
UpdateUser(user);
}
}


Would it be a good idea ? or would it be bad because it breaks the singularity rule so let the consumer class decides what to do?

Answer

It's common to work this way. If given user it hasn't been already persisted, it'll be created, otherwise, it'll be updated.

BTW, I would change the part of getting a possible user by given Id with something like this:

public interface IPersistable
{
     bool IsNew { get; }
}

public class User : IPersistable
{
    public int Id { get; set; };
    public bool IsNew => Id == 0; 
}

And then:

IPersistable persistable = user as IPersistable;
Contract.Assert(persistable != null);

if(persistable.IsNew)
{
    // Create
}
else
{
   // Update
}
Comments