Skip to content

Extensions for EFCore to help when working with a Timescale database

License

Notifications You must be signed in to change notification settings

Nickztar/EFCore.TimescaleDB.Extensions

Repository files navigation

EFCore.TimescaleDB.Extensions

NOTE: Not affiliated in anyway with Timescale DB nor is this super well made, but works for most cases.

Installation (SQL Server)

  1. Add EFCore.TimescaleDB.Extensions reference to your project.
  2. Add the following attribute to your startup/data project:
[assembly: DesignTimeServicesReference("EFCore.TimescaleDB.Extensions.DesignTimeServices, EFCore.TimescaleDB.Extensions")]
  1. Use the .ConfigureTimescale() extension of the DbContextOptionsBuilder, e.g.:
var host = Host.CreateDefaultBuilder(args)
               .ConfigureServices(
                   services =>
                   {
                       services.AddDbContext<ApplicationDbContext>(
                           options =>
                               options.UseNpgsql("<connection-string>")
                                      .ConfigureTimescale());
                   }).Build();
  1. Use the IsHyperTable(...) extension of the EntityTypeBuilder to select the entities which should be configured:
[Keyless]
public class Product 
{
    public string Name { get; set; }
    public DateTimeOffset Time { get; set; }
}

public class ApplicationDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    { }

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
        => modelBuilder.Entity<Product>().IsHyperTable(nameof(Product.Time, retentionInterval: "24 hours", chunkSize: "1 day"); // Use optional intervals
}
  1. OR: Add support for configuring via the HyperTable attribute/convention by using the AddHyperTableConfiguration() extension on ModelConfigurationBuilder
[Keyless]
[HyperTable(nameof(Time), "24 hours", "1 day")] // Optional intervals
public class Product 
{
    public string Name { get; set; }
    public DateTimeOffset Time { get; set; }
}

public class ApplicationDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    { }

    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
        => configurationBuilder.AddHyperTableConfiguration();
}
  1. Create a migration and update the database.

  2. Due to the way HyperTables works, there will be no Down command generated. To use those, either rewrite the down method. In the retention case I have added the command required as comment which can be used, but needs the table to still exist.

About

Extensions for EFCore to help when working with a Timescale database

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages