I have to write generic repository, so also method to add entities. The problem is with entities that have relationships to existing entities - they must be tracked.
So I have to write some code that will recognize which properties of some entity are used to built relationship and attach them.
How? I thought about something like that:
public async Task StoreAsync(TEntity model, CancellationToken cancellationToken = default)
{
foreach (var prop in model.GetType().GetProperties().Where(p => p.GetType().IsClass))
{
var related = prop.GetValue(model)!;
if (_dbContext.Entry(related).State == EntityState.Detached)
_dbContext.Attach(prop.GetValue(model));
}
await _dbContext.Set<TEntity>().AddAsync(model, cancellationToken);
await _dbContext.SaveChangesAsync(cancellationToken);
}
But there are multiple problems with this code - firstly, we get properties that are not value types, so record
, delegate
and class
. Delegates and records cannot be entities.
And another (im not sure if this is problem) thing is that we attach all detached entities. But what if some entity currently doesnt exist in database? What if we attach non-exsiting and will use it like existing?
So how to get all properties of instance of EF entity that are used to build relation?
I use NET7
Aucun commentaire:
Enregistrer un commentaire