Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

EF Core FirstOrDefault returns null even if entity exists

I am facing an issue where I cant fetch an entity when using .FirstOrDefaultAsync() with a GUID as the primary key.
If I fetch all entries first and then run .FirstOrDefault it works.

The entity in question also exists when inspecting the DbContext.
DbContext inspecting DbSet

Using .NET 8.0 with Entity Framework 9.0.0 and Sqlite

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public async Task AddClaim(User user, Guid claimId)
{    
    // returns null
    var claim = await context.Claims.FirstOrDefaultAsync(x => x.Id == claimId);

    // this works
    var claims = await context.Claims.ToListAsync();
    var localClaim = claims.FirstOrDefault(x => x.Id == claimId);
    
    // this throws UniqueContrain exception
    context.Claims.Add(new Domain.Entities.Claim() { Id = claimId });

    // ...
}

public class Claim
{
    public Guid Id { get; set; }
    public string Name { get; set; } = null!;
    public string Value { get; set; } = null!;
    public ICollection<User> Users { get; set; } = null!;
}

>Solution :

SQLite can store Guid values as TEXT or BLOB

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Claim>()
        .Property(c => c.Id)
        .HasConversion(v => v.ToString(), v => Guid.Parse(v));
}

This should work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading