Entity Framework Extension Methods for Saving Records

Oct 20, 2023 /
# Entity Framework
# ASP.NET

Using c# extension methods, you can make working with Entity Framework saves even easier.

Here is how it works…

Setup a BaseModel Class

The first step is to create a BaseModel abstract class. Our models will extend this class and allow us to utilize the extension method later on.

The BaseModel class has Id, CreatedDate, and ModifiedDate properties.

public abstract class BaseModel
{
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }
}

Create the Save Extension Method

Now we can setup our extension method.

public static class DbSetExtensions
{
    public static void Save<TEntity>(this DbSet<TEntity> table, TEntity o) 
        where TEntity : BaseModel
    {
        var context = table.GetService<ICurrentDbContext>().Context;

        if (o.Id == 0)
        {
            // insert
            o.CreatedAt = DateTime.UtcNow;
            table.Add(o);
            context.SaveChanges();
        }
        else
        {
            // update
            o.UpdatedAt = DateTime.UtcNow;
            table.Update(o);
            context.SaveChanges();
        }
    }
}

The Save method can be used on a DbSet object and accepts a generic object of type BaseModel.

It checks if the record has an Id. If not, were dealing with a new record and sets the CreatedAt date and saves the record.

If an Id does exist, were dealing with an existing record and set the UpdatedAt date and saves the record.

Using the Extension method

You can use the extension method like this:

public void CreateUser() 
{
    var user = new User();

    user.Name = "Kramer";
    user.Email = "kramer@example.com";

    // pretend we used DI for db, which is our DatabaseContext
    // Use extension method Save
    db.Users.Save(user);
}

Early Access

Dotnet Engine will be launching in early access soon. Signup with your email now to get notified when early access starts and a special launch price.