Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Threading.Tasks;
- using System.Reflection;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.EntityFrameworkCore.ChangeTracking;
- using Microsoft.EntityFrameworkCore.Metadata;
- using Microsoft.EntityFrameworkCore.Metadata.Internal;
- namespace Rox.Extensions.DB
- {
- public static class DbContextExtensions
- {
- public static void SyncProperty<T>(this T target, T source, IEnumerable<string> properiesName = null)
- where T : class
- {
- Type t = typeof(T);
- var properties = t.GetRuntimeProperties();
- if (properiesName != null) properties = properties.Where(p => properiesName.Contains(p.Name));
- foreach (var prop in properties)
- {
- var value = prop.GetValue(source, null);
- var valueTarget = prop.GetValue(target, null);
- if (value != null && !value.Equals(valueTarget))
- prop.SetValue(target, value);
- }
- }
- public static async Task<T> UpdateAsync<T>(this DbContext db, T entity, bool save = true)
- where T : class
- {
- var entry = db.Entry(entity);
- var primaryKey = entry.Metadata.FindPrimaryKey();
- if (primaryKey != null)
- {
- var nameKeys = primaryKey.Properties.Select(p => p.Name);
- var properies = entry.Metadata.GetProperties()?.Where(p => !nameKeys.Contains(p.Name) && !p.IsReadOnlyAfterSave && !p.IsReadOnlyBeforeSave && !p.IsShadowProperty)?.Select(p => p.Name);
- entity.SyncProperty(entity, properies);
- }
- else
- {
- entity.SyncProperty(entity);
- }
- if (save)
- await db.SaveChangesAsync();
- return entry.Entity;
- }
- public static async Task<TEntity> AddOrUpdateAsync<TEntity, TContext>(this TContext db, TEntity entity, Expression<Func<TEntity, bool>> key, bool save = true)
- where TContext : DbContext, IDisposable
- where TEntity : class
- {
- if (entity == null)
- throw new ArgumentNullException(nameof(entity));
- var dbEntity = await db.Set<TEntity>().FirstOrDefaultAsync(key);
- if (dbEntity != null)
- {
- dbEntity = await db.UpdateAsync(dbEntity, save: false);
- }
- else
- {
- dbEntity = db.Add(entity).Entity;
- }
- if (save)
- await db.SaveChangesAsync();
- return dbEntity;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement