enum property update in repository
Finally, after 48 hours, I noticed if you get an entity using FirstOrDefaultAsync and then modify the value of the properties of type enum, after calling the UpdateAsync method, the new values will be discarded. (like you have never changed them!)
But if you get the entity using GetByIdAsync, it will work!
Here is the code to demonstrate the issue:
public async Task<Discussione> Handle(RejectRequest request, CancellationToken cancellationToken)
{
var discussione = await _uow.DiscussioneRepo.GetByIdAsync(request.Id, cancellationToken)
?? throw new NotFoundException(_t[$"Discussione {0} Not Found.", request.Id]);
discussione.IDStato = StatoDiscussioneEnums.Chiusa;
discussione.IDStatoModifica = StatoModificaDiscussioneEnums.Rejected;
await _uow.DiscussioneRepo.UpdateAsync(discussione, cancellationToken);
return discussione;
}
vs
public async Task<Discussione> Handle(RejectRequest request, CancellationToken cancellationToken)
{
var discussione = await _uow.DiscussioneRepo.FirstOrDefaultAsync(new DiscussioneByIdFullSpec(request.Id), cancellationToken)
?? throw new NotFoundException(_t[$"Discussione {0} Not Found.", request.Id]);
discussione.IDStato = StatoDiscussioneEnums.Chiusa;
discussione.IDStatoModifica = StatoModificaDiscussioneEnums.Rejected;
await _uow.DiscussioneRepo.UpdateAsync(discussione, cancellationToken);
//at this point, the changes are lost
return discussione;
}
Can you post your DiscussioneByIdFullSpec here?
I suspect you added Asnotracking in your specification.
public class DiscussioneByIdFullSpec : Specification<Discussione, Discussione>
{
public DiscussioneByIdFullSpec(int id) =>
Query
.Where(p => p.IDDiscussione == id)
.Include(p => p.StatoDiscussione)
.Include(p => p.TipoDiscussione)
.Include(p => p.Messaggi).ThenInclude(a => a.Allegati)
.Include(p => p.Messaggi);
}
it is not about AsNotracking because all other types like string, int, ... get updated except Enum types.
That's a weird one. I assume you're using our default repository implementation that ships with the package? In which case the difference is between:
https://github.com/ardalis/Specification/blob/main/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/RepositoryBaseOfT.cs#L87-L90
and
https://github.com/ardalis/Specification/blob/main/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/RepositoryBaseOfT.cs#L107-L110
The former uses Find while the latter uses an IQueryable to fetch the record but I don't know why that would matter when it comes to change tracking and enum types. @fiseni any idea?
Yes, I'm using the default repository implementation.
Both FirstOrDefaultAsync and FindAsync are implemented by DbQuery (the EF's IQueryable implementation). The difference is that the FindAsync won't make a request to DB if the entity is already loaded in the EF's change tracker, it returns immediately.
Anyhow, this shouldn't affect the behavior you're facing. Something else is going on there. Are you using .NET enums? Or do you use some library that implements smart enums?
Any chance you can share a link to a project so I can take a look and debug it?
Ok, I wanted to double-check, so here is a full sample application. If you run the application, this is the output
Result using `GetByIdAsync` method.
{"Id":"537da4eb-ff1c-420a-a351-4d56dea19cb3","Name":"Name from GetByIdAsync","Type":2}
Result using `FirstOrDefaultAsync` method.
{"Id":"537da4eb-ff1c-420a-a351-4d56dea19cb3","Name":"Name from FirstOrDefaultAsync","Type":2}
So, the enum value is properly changed using both methods. Here is the full app. Please try to re-create your issue using this sample.
using Ardalis.Specification;
using Ardalis.Specification.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
var customerId = Guid.NewGuid();
// Testing with GetByIdAsync method. Deleting and creating database, just in case.
await InitializeDb();
using (var dbContext = new AppDbcontext())
{
var repository = new Repository<Customer>(dbContext);
var customer = await repository.GetByIdAsync(customerId);
ArgumentNullException.ThrowIfNull(customer);
customer.Name = "Name from GetByIdAsync";
customer.Type = CustomerType.Type2;
await repository.UpdateAsync(customer);
Console.WriteLine(JsonSerializer.Serialize(customer));
}
// Testing with FirstOrDefaultAsync method. Deleting and creating database, just in case.
await InitializeDb();
using (var dbContext = new AppDbcontext())
{
var repository = new Repository<Customer>(dbContext);
var spec = new CustomerSpec(customerId);
var customer = await repository.FirstOrDefaultAsync(spec);
ArgumentNullException.ThrowIfNull(customer);
customer.Name = "Name from FirstOrDefaultAsync";
customer.Type = CustomerType.Type2;
await repository.UpdateAsync(customer);
Console.WriteLine(JsonSerializer.Serialize(customer));
}
async Task InitializeDb()
{
using (var dbContext = new AppDbcontext())
{
await dbContext.Database.EnsureDeletedAsync();
await dbContext.Database.EnsureCreatedAsync();
var customer = new Customer
{
Id = customerId,
Name = "Some Name",
Type = CustomerType.Type1,
};
dbContext.Add(customer);
await dbContext.SaveChangesAsync();
}
}
class CustomerSpec : Specification<Customer>
{
public CustomerSpec(Guid customerId)
{
Query.Where(x => x.Id == customerId);
}
}
enum CustomerType
{
Type1 = 1,
Type2 = 2,
}
class Customer
{
public Guid Id { get; set; }
public string? Name { get; set; }
public CustomerType Type { get; set; }
}
class Repository<T> : RepositoryBase<T> where T : class
{
public Repository(AppDbcontext dbContext)
: base(dbContext)
{
}
}
class AppDbcontext : DbContext
{
public DbSet<Customer> Customers => Set<Customer>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SpecificationIssueEnumDb;Integrated Security=SSPI;ConnectRetryCount=0;");
}
I'm trying to reproduce the bug.
I have modified CustomerSpec to:
public class CustomerSpec : Specification<Customer, Customer>
{
public CustomerSpec(Guid customerId) =>
Query.Where(x => x.Id == customerId);
}
Could you please let me know how to handle the following exception?
Ardalis.Specification.SelectorNotFoundException: 'The specification must have Selector defined.'
We're throwing that exception to avoid some subtle bugs, and the message is somewhat self-explanatory. You have defined a specification with a return type, but you haven't defined the projection (you should have Query.Select in your spec). Btw, why would you have such specification Specification<Customer, Customer>?
We have two specification types:
Specification<T>- it returns the entity back.Specification<T, TResult>- it projects directly toTResulttype, but, obviously you need a select statement. For example
class CustomerSpec : Specification<Customer, string>
{
public CustomerSpec(Guid customerId)
{
Query.Where(x => x.Id == customerId);
Query.Select(x => x.Name);
}
}
//does not necessarily need to be a simple type, it can be a complex one too
class CustomerSpec : Specification<Customer, CustomerDto>
{
public CustomerSpec(Guid customerId)
{
Query.Where(x => x.Id == customerId);
Query.Select(x => new CustomerDto
{
Id = x.Id,
Name = x.Name
});
}
}
So, if you want the entity back, then just use the Specification<T> type. Also, remember that whenever you project to a different type, EF core won't track anything. I mean, that's obvious, you fetched partial information, and it can't construct the entity.
I see in your initial message that you also use a unit of work. Keep in mind that the built-in repository commits the changes on Add/Update/Delete. I suspect you have a bug somewhere along those lines, uow (some caching), projections, etc.
I couldn't manage to reproduce the bug yet.
But it exists in my actual project. as you can see in the screenshot, discussione.Oggetto is updated to "Aradis issue 290" but discussione.IDStato is not updated to StatoDiscussioneEnums.Chiusa.

but when I change var discussione = await _uow.DiscussioneRepo.FirstOrDefaultAsync(new DiscussioneByIdFullSpec(request.Id), cancellationToken) to var discussione = await _uow.DiscussioneRepo.GetByIdAsync(request.Id, cancellationToken) it works!!!
and about the
Ardalis.Specification.SelectorNotFoundException: 'The specification must have Selector defined.
I don't get any exception in my DiscussioneByIdFullSpec though I have used Specification<Discussione, Discussione>.
I checked the package versions but they are the same!
I have tried to add more codes from the actual project to make it more similar. Here is the result but it is still working:
using Ardalis.Specification;
using Ardalis.Specification.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
var customerId = Guid.NewGuid();
JsonSerializerOptions options = new()
{
ReferenceHandler = ReferenceHandler.IgnoreCycles,
WriteIndented = true
};
// Testing with GetByIdAsync method. Deleting and creating database, just in case.
await InitializeDb();
using (var dbContext = new AppDbcontext())
{
var repository = new Repository<Customer>(dbContext);
var customer = await repository.GetByIdAsync(customerId);
ArgumentNullException.ThrowIfNull(customer);
customer.Name = "Name from GetByIdAsync";
customer.CustomerTypeId = CustomerType.Type2;
customer.Addresses = new List<Address>()
{
new Address{
Street="A nice street!"
}
};
await repository.UpdateAsync(customer);
Console.WriteLine(JsonSerializer.Serialize(customer, options));
}
// Testing with FirstOrDefaultAsync method. Deleting and creating database, just in case.
await InitializeDb();
using (var dbContext = new AppDbcontext())
{
var uow = new UOW<AppDbcontext>(dbContext);
//var repository = new Repository<Customer>(dbContext);
var spec = new CustomerSpec(customerId);
var customer = await uow.CustomerRepo.FirstOrDefaultAsync(spec, cancellationToken: default);
ArgumentNullException.ThrowIfNull(customer);
customer.Name = "Name from FirstOrDefaultAsync";
Console.WriteLine($"shshsh {customer.CustomerTypeId}");
customer.CustomerTypeId = CustomerType.Type3;
await uow.CustomerRepo.UpdateAsync(customer);
Console.WriteLine(JsonSerializer.Serialize(customer, options));
}
async Task InitializeDb()
{
using (var dbContext = new AppDbcontext())
{
await dbContext.Database.EnsureDeletedAsync();
await dbContext.Database.EnsureCreatedAsync();
var t1 = new CustomerTypeTable
{
Id = CustomerType.Type1,
Name = "type 1",
Description = "Description 1"
};
var t2 = new CustomerTypeTable
{
Id = CustomerType.Type2,
Name = "type 2",
Description = "Description 2"
};
var t3 = new CustomerTypeTable
{
Id = CustomerType.Type3,
Name = "type 3",
Description = "Description 3"
};
dbContext.Add(t1);
dbContext.Add(t2);
dbContext.Add(t3);
var customer = new Customer
{
Id = customerId,
Name = "Some Name 2",
CustomerTypeId = CustomerType.Type1,
};
dbContext.Add(customer);
await dbContext.SaveChangesAsync();
}
}
public class CustomerSpec : Specification<Customer, Customer>
{
public CustomerSpec(Guid customerId)
{
Query.Where(x => x.Id == customerId).Include(c => c.Addresses).ThenInclude(x=>x.Categories);
Query.Select(x => x);
}
}
public enum CustomerType
{
Type1 = 1,
Type2 = 2,
Type3 = 3,
}
public class Customer2
{
public string? Name { get; set; }
public CustomerType CustomerTypeId { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class Customer
{
public Guid Id { get; set; }
public string? Name { get; set; }
public CustomerType CustomerTypeId { get; set; }
public CustomerTypeTable CustomerType { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class CustomerTypeTable
{
public CustomerType Id { get; set; }
public string? Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
public class Address
{
public Guid Id { get; set; }
public string? Street { get; set; }
public Guid? CustomerId { get; set; }
public virtual Customer? Customer { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
public Guid Id { get; set; }
public string? Streetxxx { get; set; }
public Guid? AddressId { get; set; }
public virtual Address? Address { get; set; }
}
public class Repository<T> : RepositoryBase<T> where T : class
{
public Repository(AppDbcontext dbContext)
: base(dbContext)
{
}
}
public class AppDbcontext : DbContext
{
public DbSet<Customer> Customers => Set<Customer>();
public DbSet<Address> Addresses => Set<Address>();
public DbSet<Category> Xxxes => Set<Category>();
public DbSet<CustomerTypeTable> CustomerTypes => Set<CustomerTypeTable>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=SpecificationIssueEnumDb;Integrated Security=SSPI;ConnectRetryCount=0;");
}
public interface IUOW
{
public IRepository<Customer> CustomerRepo { get; }
public IRepository<Address> AddressRepo { get; }
public IRepository<CustomerTypeTable> CustomerTypeRepo { get; }
}
public class UOW<TContext> : IUOW where TContext : AppDbcontext
{
private AppDbcontext _db;
public UOW(TContext dbContext)
{
_db = dbContext;
}
private IRepository<Customer> _customerRepo;
public IRepository<Customer> CustomerRepo => _customerRepo ??= new ApplicationDbRepository<Customer>(_db);
private IRepository<Address> _addressRepo;
public IRepository<Address> AddressRepo => _addressRepo ??= new ApplicationDbRepository<Address>(_db);
private IRepository<CustomerTypeTable> _customerTypeRepo;
public IRepository<CustomerTypeTable> CustomerTypeRepo => _customerTypeRepo ??= new ApplicationDbRepository<CustomerTypeTable>(_db);
}
// The Repository for the Application Db
// I(Read)RepositoryBase<T> is from Ardalis.Specification
/// <summary>
/// The regular read/write repository for an aggregate root.
/// </summary>
public interface IRepository<T> : IRepositoryBase<T>
where T : class
{
}
/// <summary>
/// The read-only repository for an aggregate root.
/// </summary>
public interface IReadRepository<T> : IReadRepositoryBase<T>
where T : class
{
}
/// <summary>
/// A special (read/write) repository for an aggregate root,
/// that also adds EntityCreated, EntityUpdated or EntityDeleted
/// events to the DomainEvents of the entities before adding,
/// updating or deleting them.
/// </summary>
public interface IRepositoryWithEvents<T> : IRepositoryBase<T>
where T : class
{
}
public class ApplicationDbRepository<T> : RepositoryBase<T>, IReadRepository<T>, IRepository<T>
where T : class
{
public ApplicationDbRepository(AppDbcontext dbContext)
: base(dbContext)
{
}
}
Database schema:

the project is not code-first.
You should check what is going on in the ChangeTracker. Just for testing purposes inject the DbContext in that class. Put a breakpoint at lines 32, 35, 37, and check what's going on in the tracker. Starting with EFCore 6, there is an easy way to peek at the tracker's content. In the local window, check the DbContext -> ChangeTracker -> DebugView -> LongView .
One more important note. I notice you're using MediatR? By default, the mediator handlers are registered as transient in DI, not as scoped.
Ok, here is the result:
when I use FirstOrDefaultAsync(new DiscussioneByIdFullSpec(id), cancellationToken) :
before calling UpdateAsync:
Iscritto {IDIscritto: 1056079} Unchanged
IDIscritto: 1056079 PK
CAPAlternativo: <null>
Cap: '34077'
Cellulare: '8888888888'
Discussioni: <null>
Messaggio {IDMessaggio: 129} Unchanged
IDMessaggio: 129 PK
DataCreazione: '30/08/2022 16:48:54'
IDDiscussione: 95 FK
Testo: '<p>Inizia a scrivere il messaggio qui... </p>'
UserIdCreazione: 'c2f0c0f2-7b8d-44f4-8ef2-26d44cce03e7'
Allegati: []
Discussione: <null>
StatoDiscussione {IDStatoDiscussione: Risposta} Unchanged
IDStatoDiscussione: 'Risposta' PK
Descrizione: 'Discussione a cui è stato risposto'
Titolo: 'Risposta'
Discussioni: <null>
StatoModificaDiscussione {Id: Pending} Unchanged
Id: 'Pending' PK
Descrizione: 'Pending'
Titolo: 'Pending'
Discussioni: <null>
TipoDiscussione {IDTipoDiscussione: ModificaNome} Unchanged
IDTipoDiscussione: 'ModificaNome' PK
Descrizione: 'Discussione di Modifica del Nome'
Titolo: 'Modifica del Nome'
Discussioni: <null>
after calling UpdateAsync:
Discussione {IDDiscussione: 95} Unchanged
IDDiscussione: 95 PK
DataAssegnazione: <null>
DataCreazione: '30/08/2022 16:48:54'
DataModifica: <null>
DatoFinale: 'Lando'
DatoIniziale: 'LANDO new'
IDAzienda: <null> FK
IDIscritto: 1056079 FK
IDStato: 'Risposta' FK
IDStatoModifica: 'Pending' FK
IDTipo: 'ModificaNome' FK
Oggetto: 'Aradis issue 290 new'
UserIdAssegnazione: <null>
UserIdCreazione: 'c2f0c0f2-7b8d-44f4-8ef2-26d44cce03e7'
UserIdModifica: <null>
Azienda: <null>
Iscritto: {IDIscritto: 1056079}
Messaggi: [{IDMessaggio: 129}]
StatoDiscussione: {IDStatoDiscussione: Risposta}
StatoModificaDiscussione: {Id: Pending}
TipoDiscussione: {IDTipoDiscussione: ModificaNome}
Iscritto {IDIscritto: 1056079} Unchanged
IDIscritto: 1056079 PK
CAPAlternativo: <null>
Cap: '34077'
Discussioni: [{IDDiscussione: 95}]
Messaggio {IDMessaggio: 129} Unchanged
IDMessaggio: 129 PK
DataCreazione: '30/08/2022 16:48:54'
IDDiscussione: 95 FK
Testo: '<p>Inizia a scrivere il messaggio qui... </p>'
UserIdCreazione: 'c2f0c0f2-7b8d-44f4-8ef2-26d44cce03e7'
Allegati: []
Discussione: {IDDiscussione: 95}
StatoDiscussione {IDStatoDiscussione: Risposta} Unchanged
IDStatoDiscussione: 'Risposta' PK
Descrizione: 'Discussione a cui è stato risposto'
Titolo: 'Risposta'
Discussioni: [{IDDiscussione: 95}]
StatoModificaDiscussione {Id: Pending} Unchanged
Id: 'Pending' PK
Descrizione: 'Pending'
Titolo: 'Pending'
Discussioni: [{IDDiscussione: 95}]
TipoDiscussione {IDTipoDiscussione: ModificaNome} Unchanged
IDTipoDiscussione: 'ModificaNome' PK
Descrizione: 'Discussione di Modifica del Nome'
Titolo: 'Modifica del Nome'
Discussioni: [{IDDiscussione: 95}]
and then when I use GetByIdAsync:
before calling UpdateAsync :
Discussione {IDDiscussione: 95} Unchanged
IDDiscussione: 95 PK
DataAssegnazione: <null>
DataCreazione: '30/08/2022 16:48:54'
DataModifica: <null>
DatoFinale: 'Lando'
DatoIniziale: 'LANDO new'
IDAzienda: <null> FK
IDIscritto: 1056079 FK
IDStato: 'Chiusa' FK Originally 'Risposta'
IDStatoModifica: 'Pending' FK
IDTipo: 'ModificaNome' FK
Oggetto: 'Aradis issue 290 new' Originally 'Test'
UserIdAssegnazione: <null>
UserIdCreazione: 'c2f0c0f2-7b8d-44f4-8ef2-26d44cce03e7'
UserIdModifica: <null>
Azienda: <null>
Iscritto: <null>
Messaggi: <null>
StatoDiscussione: <null>
StatoModificaDiscussione: <null>
TipoDiscussione: <null>
and after calling UpdateAsync:
Discussione {IDDiscussione: 95} Unchanged
IDDiscussione: 95 PK
DataAssegnazione: <null>
DataCreazione: '30/08/2022 16:48:54'
DataModifica: <null>
DatoFinale: 'Lando'
DatoIniziale: 'LANDO new'
IDAzienda: <null> FK
IDIscritto: 1056079 FK
IDStato: 'Chiusa' FK
IDStatoModifica: 'Pending' FK
IDTipo: 'ModificaNome' FK
Oggetto: 'Aradis issue 290 new'
UserIdAssegnazione: <null>
UserIdCreazione: 'c2f0c0f2-7b8d-44f4-8ef2-26d44cce03e7'
UserIdModifica: <null>
Azienda: <null>
Iscritto: <null>
Messaggi: <null>
StatoDiscussione: <null>
StatoModificaDiscussione: <null>
TipoDiscussione: <null>
Ok, it's kind of obvious what is going on. As you can see in the first results, the Discussione entity is not tracked at all. You have a peculiar infrastructure here, and I can't figure out what exactly you're doing. How did you fetch the Iscritto?
Anyhow, the issue revolves around that, why Discussione is not loaded.
Update the spec as follows (remove the return type)
public class DiscussioneByIdFullSpec : Specification<Discussione>
{
public DiscussioneByIdFullSpec(int id)
{
Query.Where(p => p.IDDiscussione == id)
.Include(p => p.StatoDiscussione)
.Include(p => p.TipoDiscussione)
.Include(p => p.Messaggi)
.ThenInclude(a => a.Allegati)
.Include(p => p.Messaggi);
}
}
PS. Also, I see that you have a repository with events. Are you sure that when the status is changed you're not publishing some event? Are you using domain events? How and when do you dispatch those events?
Please consider the fact that Oggetto is updated in both scenarios.
From the value 'Test' to 'Aradis issue 290 new'.
Iscritto is not included in the DiscussioneByIdFullSpec and I guess it shouldn't be tracked.
I'm really sorry, but can't help you here. I have to see what exactly you're doing. Would be great if you can reproduce the issue in the sample (although it doesn't seem the issue is the library). Or, send me a link to your project privately, and I'll try to be of help.
Closing as inactive.