Esempio n. 1
0
 public static void AddOrUpdate(this Microsoft.EntityFrameworkCore.DbContext ctx, IEnumerable <object> entityList)
 {
     foreach (var entry in entityList)
     {
         AddOrUpdate(ctx, entry);
     }
 }
Esempio n. 2
0
        public static void AddOrUpdate(this Microsoft.EntityFrameworkCore.DbContext ctx, object entity)
        {
            var entry = ctx.Entry(entity);

            switch (entry.State)
            {
            case EntityState.Detached:
                ctx.Add(entity);
                break;

            case EntityState.Modified:
                ctx.Update(entity);
                break;

            case EntityState.Added:
                ctx.Add(entity);
                break;

            case EntityState.Unchanged:
                //item already in db no need to do anything
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Esempio n. 3
0
    /// <summary>
    /// 根据sql语句查询并返回动态列表
    /// </summary>
    /// <param name="db"></param>
    /// <param name="sql"></param>
    /// <returns></returns>
    public static List <dynamic> GetFromSql(this Microsoft.EntityFrameworkCore.DbContext db, string sql)
    {
        var conn = db.Database.GetDbConnection();
        var cmd  = conn.CreateCommand();

        cmd.CommandText = sql;
        conn.Open();
        var list   = new List <dynamic>();
        var reader = cmd.ExecuteReader();

        if (reader.HasRows)
        {
            var columns = new string[reader.FieldCount];
            for (var i = 0; i < reader.FieldCount; i++)
            {
                columns[i] = reader.GetName(i);
            }
            while (reader.Read())
            {
                dynamic model = new ExpandoObject();
                var     dict  = (IDictionary <string, object>)model;
                for (var i = 0; i < reader.FieldCount; i++)
                {
                    dict[columns[i]] = reader[i];
                }
                if (dict.Count > 0)
                {
                    list.Add(model);
                }
            }
        }
        conn.Close();
        return(list);
    }
Esempio n. 4
0
 public HomeController(ILogger <HomeController> logger, TestDBContext _dbt)
 {
     _logger = logger;
     dbt     = _dbt;
     //cfg = _cfg;
     _TestDBContext = (TestDBContext)_dbt;
 }
Esempio n. 5
0
        private static void WritePerf(Microsoft.EntityFrameworkCore.DbContext dbContext)
        {
            var trackingCount = dbContext.ChangeTracker.Entries().Count();
            var mem           = GC.GetTotalMemory(true) / 1024 / 1024;

            Console.WriteLine($"\t {trackingCount} ChangeTracker Entries. Total Memory after GC: {mem}mb");
            Console.WriteLine();
        }
Esempio n. 6
0
        protected internal Repository(Microsoft.EntityFrameworkCore.DbContext databaseContext) : base()
        {
            DatabaseContext =
                databaseContext ??
                throw new System.ArgumentNullException(paramName: nameof(databaseContext));

            DbSet = DatabaseContext.Set <T>();
        }
Esempio n. 7
0
 public EFRepository(Microsoft.EntityFrameworkCore.DbContext dbContext)
 {
     if (dbContext == null)
     {
         throw new ArgumentNullException("dbContext");
     }
     DbContext = dbContext;
     DbSet     = DbContext.Set <T>();
 }
Esempio n. 8
0
        public EfRepository(Microsoft.EntityFrameworkCore.DbContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            _context = context;
            _set     = _context.Set <TEnity>();
        }
        public static bool InitialMigrationApplied(this Microsoft.EntityFrameworkCore.DbContext context)
        {
            var allAppliedMigrations = context.GetService <IHistoryRepository>()
                                       .GetAppliedMigrations()
                                       .Select(x => x.MigrationId)
                                       .ToArray();

            return(allAppliedMigrations.Any(x => x.EndsWith(InitialMigrationId)) &&
                   !allAppliedMigrations.Contains(SeedInitialDataMigrationId));
        }
Esempio n. 10
0
 public LogEventHandler(
     UserProvider userAcessor,
     IServiceProvider serviceProvider,
     DbContextProvider dbContext,
     IEnumerable <IgnoredEntity> listaNegras)
 {
     this.userAcessor = userAcessor(serviceProvider);
     this.dbContext   = dbContext(serviceProvider);
     this.listaNegras = listaNegras;
     this.LogType     = typeof(EventLog).Name;
 }
Esempio n. 11
0
        private static bool AllMigrationsApplied(this Microsoft.EntityFrameworkCore.DbContext context)
        {
            var applied = context.GetService <IHistoryRepository>()
                          .GetAppliedMigrations()
                          .Select(m => m.MigrationId);

            var total = context.GetService <IMigrationsAssembly>()
                        .Migrations
                        .Select(m => m.Key);

            return(!total.Except(applied).Any());
        }
Esempio n. 12
0
        /// <summary>
        ///     Auto initialize or update currently date time for any class based on class ModelBase
        /// </summary>
        public static void AddAuditInfo(this Microsoft.EntityFrameworkCore.DbContext dbContext)
        {
            var entries = dbContext.ChangeTracker.Entries().Where(e =>
                                                                  e.Entity is ModelBase && (e.State is EntityState.Added || e.State is EntityState.Modified));

            foreach (var entry in entries)
            {
                if (entry.State is EntityState.Added)
                {
                    ((ModelBase)entry.Entity).CreatedAt = DateTime.UtcNow;
                }
                ((ModelBase)entry.Entity).UpdatedAt = DateTime.UtcNow;
            }
        }
Esempio n. 13
0
        private static void TurnOnSnapshotIsolation(Microsoft.EntityFrameworkCore.DbContext context)
        {
            var conn         = context.Database.GetDbConnection();
            var providerName = conn.GetType().Name;

            if (providerName != "SqlConnection")
            {
                return;
            }

            conn.Open();
            context.Database.ExecuteSqlCommand(
                $"ALTER DATABASE CURRENT  SET ALLOW_SNAPSHOT_ISOLATION ON;ALTER DATABASE CURRENT SET READ_COMMITTED_SNAPSHOT ON; ");
            conn.Close();
        }
 public static DataSet GetQueryDatatable(this Microsoft.EntityFrameworkCore.DbContext context, string sqlQuery, SqlParameter[] sqlParam = null, CommandType type = CommandType.StoredProcedure)
 {
     using (DbCommand cmd = context.Database.GetDbConnection().CreateCommand())
     {
         cmd.Connection  = context.Database.GetDbConnection();
         cmd.CommandType = type;
         if (sqlParam != null)
         {
             cmd.Parameters.AddRange(sqlParam);
         }
         cmd.CommandText = sqlQuery;
         using (DbDataAdapter dataAdapter = new SqlDataAdapter())
         {
             dataAdapter.SelectCommand = cmd;
             DataSet ds = new DataSet();
             dataAdapter.Fill(ds);
             return(ds);
         }
     }
 }
Esempio n. 15
0
        public static void Configure(this Microsoft.EntityFrameworkCore.DbContext context, DbContextOptionsBuilder optionsBuilder, string connectionStringName)
        {
            var conn = DataConfigurationSettings.Instance.Connections.FirstOrDefault(x => x.Name.IsEqual(connectionStringName));

            if (conn == null)
            {
                throw new ArgumentException($"Can not find connection with name '{connectionStringName}'", "connectionName");
            }

            switch (DataConfigurationSettings.Instance.StoreType)
            {
            case DataStoreType.SqlServer:
                optionsBuilder.UseSqlServer(conn.Value);
                break;

            case DataStoreType.PostgreSql:
                optionsBuilder.UseNpgsql(conn.Value);
                break;
            }
        }
Esempio n. 16
0
 public TruncateHandler(Microsoft.EntityFrameworkCore.DbContext dbContext)
 {
     _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
 }
Esempio n. 17
0
 public BaseRepository(Microsoft.EntityFrameworkCore.DbContext context)
 {
     Context  = context;
     Entities = Context.Set <TEntity>();
 }
Esempio n. 18
0
 public Repository(Microsoft.EntityFrameworkCore.DbContext context)
 {
 }
Esempio n. 19
0
 public GenericRepository(DbContext context)
 {
     this.Context = context;
     this.DbSet   = context.Set <TE>();
 }
Esempio n. 20
0
 public CouponsRepository(Microsoft.EntityFrameworkCore.DbContext dbContext)
 {
     _context = dbContext;
     _coupons = _context.Set <Coupon>();
 }
Esempio n. 21
0
        /// <summary>
        /// Gets the entity metadata for specified db ctx;
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dbCtx"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static Microsoft.EntityFrameworkCore.Metadata.IEntityType GetEntityMetadata <T>(this Microsoft.EntityFrameworkCore.DbContext dbCtx, T obj)
        {
            //var type = typeof(T);
            var type = obj.GetType();

            //do a cache loolup first
            if (EntitiesMetadataCache.ContainsKey(dbCtx) && EntitiesMetadataCache[dbCtx] != null &&
                EntitiesMetadataCache[dbCtx].ContainsKey(type))
            {
                return(EntitiesMetadataCache[dbCtx][type]);
            }

            var mapping = dbCtx.Model.FindEntityType(type);

            //cache the results
            if (!EntitiesMetadataCache.ContainsKey(dbCtx))
            {
                EntitiesMetadataCache[dbCtx] = new Dictionary <Type, Microsoft.EntityFrameworkCore.Metadata.IEntityType>();
            }
            EntitiesMetadataCache[dbCtx].Add(type, mapping);

            return(mapping);
        }
Esempio n. 22
0
        /// <summary>
        /// Gets a mapped column name
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dbCtx"></param>
        /// <param name="obj"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string GetTableColumnName <T>(this Microsoft.EntityFrameworkCore.DbContext dbCtx, T obj, string propertyName)
        {
            var metaData = dbCtx.GetEntityMetadata(obj);

            return(metaData.GetProperties().FirstOrDefault(p => p.Name == propertyName)?.GetColumnName());
        }
 public ProductRepository(Microsoft.EntityFrameworkCore.DbContext db) : base(db)
 {
     this.db = (ShopApplicationDbContext)db;
 }
Esempio n. 24
0
 public GenericRepository(Microsoft.EntityFrameworkCore.DbContext context)
 {
     this.Context = context;
     this.DbSet   = context.Set <T>();
 }
Esempio n. 25
0
 public BaseRepository(AppDbContext appDbContext)
 {
     this.dbContext = appDbContext ?? throw new ArgumentNullException("dbContext can not be null.");
     this.dbSet     = appDbContext.Set <TEntity>();
 }
Esempio n. 26
0
 public Repository(CoreDbContext prandoDbContext)
 {
     _prandoDbContext = prandoDbContext;
 }
Esempio n. 27
0
 public BookingsRepository(Microsoft.EntityFrameworkCore.DbContext context) : base(context)
 {
 }
 public SalesDetailsRepository(Microsoft.EntityFrameworkCore.DbContext db) : base(db)
 {
     this.db = db;
 }
Esempio n. 29
0
 public Repository(Microsoft.EntityFrameworkCore.DbContext dataContext)
 {
     DbSet = dataContext.Set <T>();
 }
Esempio n. 30
0
 public UserRepository(Microsoft.EntityFrameworkCore.DbContext dbContext) : base(dbContext)
 {
     _dbContext = dbContext;
 }