FlexLabs.Upsert icon indicating copy to clipboard operation
FlexLabs.Upsert copied to clipboard

Upsert not working on a simple example

Open goutamvenkatCatalan opened this issue 2 years ago • 1 comments
trafficstars

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Configurations;
using DotNet.Testcontainers.Containers;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

var _dbContainer = new TestcontainersBuilder<PostgreSqlTestcontainer>()
    .WithDatabase(new PostgreSqlTestcontainerConfiguration
    {
        Database = "db",
        Username = "postgres",
        Password = "postgres",
    })
    .WithImage("postgres:latest")
    .WithPortBinding(80, true)
    .WithCleanUp(true)
    .Build();

await _dbContainer.StartAsync();
var dbContext = CreateContext();
dbContext.Database.EnsureCreated();

dbContext.StatusEntities.Add(new Status()
{
    Id = 1,
    LastChecked = DateTime.UtcNow - TimeSpan.FromDays(1),
    Name = "blah"
});

await dbContext.SaveChangesAsync();

dbContext.StatusEntities.Upsert(new Status()
{
    Id = 1,
    Name = "mine"
}).Run();

Console.WriteLine(JsonConvert.SerializeObject(await dbContext.StatusEntities.ToListAsync()));

ApplicationContext CreateContext()
{
    var connectionString = _dbContainer.ConnectionString;
    return new ApplicationContext(
        new DbContextOptionsBuilder<ApplicationContext>().UseNpgsql(connectionString).Options);
}

public class Status
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long Id { get; set; }
    public string Name { get; set; }
    public DateTime LastChecked { get; set; }
}


public class ApplicationContext : DbContext
{
    public ApplicationContext(DbContextOptions<ApplicationContext> options)
        : base(options)
    {
    }
    
    public DbSet<Status> StatusEntities { get; set; }
}

I have a console app here that tries to update StatusEntity on the Id column, however the name field doesn't change. Any ideas as to what's happening here?

goutamvenkatCatalan avatar Mar 14 '23 04:03 goutamvenkatCatalan

Hello did you have any luck with this? I am getting an issue as well

42P01: relation "LiveTelemetry" does not exist

POSITION: 13

On this code here

                await _context.LiveTelemetry.UpsertRange(inputs)
                    .On(c => new { c.MessageSourceId, c.TelemetryMetricName, c.TimeStamp })
                    .NoUpdate()
                    .RunAsync(); 

                await _context.SaveChangesAsync();

I think the problem is it does not work with DBContexts that UseNpgsql I suspect it may only accept UseSqlServer

jimbrew avatar Jul 28 '23 11:07 jimbrew