4
I’ve been looking for a method to check if an object exists in the base, if it exists, run a update
, if there is no, insert
.
I couldn’t find anything anywhere that would suit me, so I made the following code:
public static void InsertOrUpdate<T>(this DbSet<T> dbSet, T entity) where T : class
{
PropertyInfo pId = entity.GetType().GetProperty("Id");
if (pId != null)
{
object valId = pId.GetValue(entity);
if (dbSet.Any(p => p.GetType().GetProperty("Id").GetValue(p).ToString() == valId.ToString()))
{
T e = dbSet.Where(p => p.GetType().GetProperty("Id").GetValue(p).ToString() == valId.ToString()).FirstOrDefault();
foreach (PropertyInfo p in e.GetType().GetProperties().Where(x => x.CanWrite && x.Name != "Id"))
{
p.SetValue(e, p.GetValue(entity));
}
dbSet.Update(e);
}
else
{
dbSet.Add(entity);
}
}
}
As I always read something about slowing down the use of Reflection, and I try to optimize the code, the question is simple:
There is another way to do this method, or improve this code ?
At first, I have no problem with it, and it works perfectly. Just a matter of not hacking and optimizing the code.
I am using ASP.NET Core, with Entity Framework Core and I have no practice with these.
Edit:
I got that other method (looks better, but there’s still reflection
):
public static void InsertOrUpdate<T>(this ApplicationDbContext context, T entity) where T : class
{
PropertyInfo ps = entity.GetType().GetProperty("Id");
if (ps != null)
{
DbSet<T> set = context.Set<T>();
if (set.Any(x => ps.GetValue(x).ToString() == ps.GetValue(entity).ToString()))
{
context.Entry(entity).State = EntityState.Modified;
}
else
{
set.Add(entity);
}
}
}
Thank you @Virgilio, for today I’m already stopping, but tomorrow I implement and give the feedback. Good night!
– Rovann Linhalis
It worked perfectly @Virgilio, thank you very much!
– Rovann Linhalis