using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using EasyDevCore.Common;
using System.Data;
using System.Runtime.CompilerServices;
using System.Dynamic;
using System.Collections;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query;
using System.Linq.Expressions;
namespace EasyDevCore.Database
{
///
///
///
public static class DbSetExtensions
{
///
/// Gets the context.
///
/// The type of the entity.
/// The database set.
///
public static DbContext GetContext(this DbSet dbSet) where TEntity : class
{
object internalSet = dbSet
.GetType()
.GetField("_internalSet", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(dbSet);
object internalContext = internalSet
.GetType()
.BaseType
.GetField("_internalContext", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(internalSet);
return (DbContext)internalContext
.GetType()
.GetProperty("Owner", BindingFlags.Instance | BindingFlags.Public)
.GetValue(internalContext, null);
}
///
/// Saves the change.
///
/// The type of the entity.
/// The database set.
///
public static int SaveChange(this DbSet dbSet) where TEntity : class
{
var context = (EasyDbContext)dbSet.GetContext();
return context.SaveChangeEntity(dbSet.GetType());
}
///
/// Saves the change asynchronous.
///
/// The type of the entity.
/// The database set.
///
public static async Task SaveChangeAsync(this DbSet dbSet) where TEntity : class
{
var context = (EasyDbContext)dbSet.GetContext();
return await context.SaveChangeEntityAsync(dbSet.GetType()).ConfigureAwait(false);
}
}
}