• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Data.DbContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Data.DbContext的典型用法代码示例。如果您正苦于以下问题:C# DbContext类的具体用法?C# DbContext怎么用?C# DbContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



DbContext类属于System.Data命名空间,在下文中一共展示了DbContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: PreSaveChanges

        /// <summary>Pre save changes.</summary>
        /// <param name="audit">The audit to use to add changes made to the context.</param>
        /// <param name="context">The context used to audits and saves all changes made.</param>
        public static void PreSaveChanges(Audit audit, DbContext context)
        {
#if EF5 || EF6
            var objectContext = context.GetObjectContext();
            objectContext.DetectChanges();

            var changes = objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted);

            foreach (var objectStateEntry in changes)
            {
                if (objectStateEntry.IsRelationship)
                {
                    if (objectStateEntry.State == EntityState.Added && audit.Configuration.IncludeRelationAdded)
                    {
                        AuditRelationAdded(audit, objectStateEntry);
                    }
                    else if (objectStateEntry.State == EntityState.Deleted && audit.Configuration.IncludeRelationDeleted)
                    {
                        AuditRelationDeleted(audit, objectStateEntry);
                    }
                }
                else
                {
                    if (objectStateEntry.State == EntityState.Added && audit.Configuration.IncludeEntityAdded)
                    {
                        AuditEntityAdded(audit, objectStateEntry);
                    }
                    else if (objectStateEntry.State == EntityState.Deleted && audit.Configuration.IncludeEntityDeleted)
                    {
                        AuditEntityDeleted(audit, objectStateEntry);
                    }
                    else if (objectStateEntry.State == EntityState.Modified && audit.Configuration.IncludeEntityModified)
                    {
                        AuditEntityModified(audit, objectStateEntry);
                    }
                }
            }
#elif EF7
            context.ChangeTracker.DetectChanges();
            var manager = context.ChangeTracker.GetStateManager();
            var entries = manager.Entries;

            foreach (var entry in entries)
            {
                if (entry.EntityState == EntityState.Added)
                {
                    
                }
                else if (entry.EntityState == EntityState.Deleted)
                {

                }
                else if (entry.EntityState == EntityState.Modified)
                {
                    
                }
            }
#endif

        }
开发者ID:DebugOfTheRoad,项目名称:EntityFramework-Plus,代码行数:63,代码来源:PreSaveChanges.cs


示例2: LoadStub

        internal static object LoadStub(Type t, string primaryKeyName, object id, DbContext db)
        {
            var cachedEnt =
                    db.ChangeTracker.Entries().Where(x => ObjectContext.GetObjectType(x.Entity.GetType()) == t).SingleOrDefault(x =>
                    {
                        Type entType = x.Entity.GetType();
                        object value = entType.InvokeMember(primaryKeyName, System.Reflection.BindingFlags.GetProperty, null, x.Entity, new object[] { });

                        return value.Equals(id);
                    });

            if (cachedEnt != null)
            {
                return cachedEnt.Entity;
            }
            else
            {
                object stub = Activator.CreateInstance(t);

                t.InvokeMember(primaryKeyName, System.Reflection.BindingFlags.SetProperty, null, stub, new object[] { id });

                db.Entry(stub).State = EntityState.Unchanged;

                return stub;
            }
        }
开发者ID:MichaelBuen,项目名称:DitTO,代码行数:26,代码来源:EfPoco.cs


示例3: Migrate

        public MigrationResult Migrate(DbContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (!context.IsAzureDatabase())
            {
                return new MigrationResult
                {
                    MigrationWasApplied = true,
                    Log = "Database is not an Azure SQL database so no action taken."
                };
            }

            var sql =
                [email protected]"
alter database {context.Database.Connection.Database} 
modify (MAXSIZE = {MaxSize},
        EDITION = '{Edition}',
        SERVICE_OBJECTIVE = '{ServiceObjective}')";

            context.Database.ExecuteSqlCommand(sql);

            return new MigrationResult
            {
                MigrationWasApplied = true,
                Log = sql
            };
        }
开发者ID:KimberlyPhan,项目名称:Its.Cqrs,代码行数:31,代码来源:AzureSqlDbMigrator.cs


示例4: GetDBAdapterBase

 /// <summary>
 /// 根据数据库类型获取适配器
 /// </summary>
 /// <param name="dbContext"></param>
 /// <returns></returns>
 public static DBAdapterBase GetDBAdapterBase(DbContext dbContext)
 {
     DBAdapterBase db = null;
     switch (dbContext.DBHelper.CurrentDBType)
     {
         case CoreHelper.DBType.MSSQL:
             db = new MSSQLDBAdapter(dbContext);
             break;
         case CoreHelper.DBType.MSSQL2000:
             db = new MSSQL2000DBAdapter(dbContext);
             break;
         case CoreHelper.DBType.ACCESS:
             break;
         case CoreHelper.DBType.MYSQL:
             db = new MySQLDBAdapter(dbContext);
             break;
         case CoreHelper.DBType.ORACLE:
             db = new ORACLEDBAdapter(dbContext);
             break;
     }
     if (db == null)
     {
         throw new Exception("找不到对应的DBAdapte" + dbContext.DBHelper.CurrentDBType);
     }
     return db;
 }
开发者ID:yhhno,项目名称:CRL3,代码行数:31,代码来源:DBAdapterBase.cs


示例5: SqlCommandToDynamicEntity

        /// <summary>
        /// sample invocation code
        /// int codPers = 21024;
        /// string tipPers = "fiz";
        /// SqlCommand sqlCommand = new SqlCommand("dbo.GetSolduri");
        /// sqlCommand.CommandType = CommandType.StoredProcedure;
        /// sqlCommand.Parameters.AddWithValue("@codPers", codPers);
        /// sqlCommand.Parameters.AddWithValue("@tipPers", tipPers);
        /// return HelperController.SqlCommandToDynamicEntity(repository.Context, sqlCommand);
        /// </summary>
        /// <param name="context"></param>
        /// <param name="sqlCommand"></param>
        /// <returns></returns>
        public static List<object> SqlCommandToDynamicEntity(DbContext context, SqlCommand sqlCommand)
        {
            string dynamicEntity = "DynamicEntity";
            bool isFirstRow = true;
            AssemblyName assemblyName = new AssemblyName("MyAssembly");
            AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
            TypeBuilder typeBuilder = moduleBuilder.DefineType(dynamicEntity, TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass |
                                                    TypeAttributes.BeforeFieldInit, typeof(System.Object));

            List<object> entities = new List<object>();
            // Get the type contained in the name string
            Type type = typeBuilder.AsType();

            DataTable dt = new DataTable();

            ///sample invocation code
            //int codPers = 21024;
            //string tipPers = "fiz";
            //sqlCommand = new SqlCommand("dbo.GetSolduri");
            //sqlCommand.CommandType = CommandType.StoredProcedure;
            //sqlCommand.Parameters.AddWithValue("@codPers", codPers);
            //sqlCommand.Parameters.AddWithValue("@tipPers", tipPers);

            using (SqlConnection con = new SqlConnection(context.Database.Connection.ConnectionString))
            {
                using (sqlCommand)
                {
                    sqlCommand.Connection = con;
                    con.Open();
                    SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
                    da.Fill(dt);
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (isFirstRow)
                        {
                            isFirstRow = false;
                            foreach (DataColumn col in dt.Columns)
                            {
                                typeBuilder.DefineField(col.ColumnName, (dr[col]).GetType(), FieldAttributes.Public);
                            }

                            type = typeBuilder.CreateType();
                            var prop = type.GetFields().First().Name;
                        }
                        // create an instance of that type
                        object entity = Activator.CreateInstance(type);
                        foreach (DataColumn col in dt.Columns)
                        {
                            if (dr[col] == null || dr[col] == System.DBNull.Value) continue;
                            FieldInfo prop = type.GetField(col.ColumnName);
                            // Set the value of the given property on the given instance
                            prop.SetValue(entity, dr[col]);
                        }
                        entities.Add(entity);
                    }
                    return entities;
                }
            }
        }
开发者ID:viorelfilip,项目名称:Impotax2,代码行数:73,代码来源:HelperController.cs


示例6: SetUp

        public void SetUp()
        {
            DbContextBuilder<DbContext> builder = new DbContextBuilder<DbContext>("DefaultDb", new[] { "QV.Tests" }, true, true);
            context = builder.BuildDbContext();

            customerRepository = new QV.Tests.Data.Lab.CustomerRepository(context);
            repository = new QV.Data.EntityFramework.Lab.GenericRepository(context);
        }
开发者ID:sarma,项目名称:QuantumValue,代码行数:8,代码来源:WithoutStorageTest.cs


示例7: SetUp

        public void SetUp()
        {
            var builder = new DbContextBuilder<DbContext>("DefaultDb", new[] { "Infrastructure.Tests" }, true, true);
            this.context = builder.BuildDbContext();

            this.customerRepository = new CustomerRepository(this.context);
            this.repository = new GenericRepository(this.context);
        }
开发者ID:CSharpDev,项目名称:Dev.All,代码行数:8,代码来源:WithoutStorageTest.cs


示例8: OperationRepository

 public OperationRepository(DbContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context", "DbContext should not be empty");
     }
     Context = context;
 }
开发者ID:al-main,项目名称:vabank,代码行数:8,代码来源:OperationRepository.cs


示例9: AssignStubx

        internal static void AssignStubx(object poco, DbContext db)
        {
            IEnumerable<PropertyMapping> piNeedStub = Mapper.StubsNeeded(poco.GetType());

            foreach (PropertyMapping pm in piNeedStub)
            {
                // pm.PropertyPoco.First().   e.g. Customer of Customer.CustomerId.    Customer is PropertyPoco[0], CustomerId is PropertyPoco[1]
                PropertyInfo pocoForeign = poco.GetType().GetProperty(pm.PropertyPoco[0], BindingFlags.Public | BindingFlags.Instance);
                if (pocoForeign == null) continue;

                object val = pocoForeign.GetValue(poco, null);

                if (val != null)
                {
                    PropertyInfo pocoForeignId = pocoForeign.PropertyType.GetProperty(pm.PropertyPoco.Last(), BindingFlags.Public | BindingFlags.Instance);

                    object id = pocoForeignId.GetValue(val, null);

                    pocoForeign.SetValue(poco, LoadStub(pocoForeign.PropertyType, pm.PropertyPoco.Last(), id, db), null);
                }
                else
                {
                    // foreign key is null'd

                    // nullable foreign key association
                    // http://www.codetuning.net/blog/post/Understanding-Entity-Framework-Associations.aspx

                    var dummy = pocoForeign.GetValue(poco, null); // work-around

                    pocoForeign.SetValue(poco, val, null);
                }

            }

            IEnumerable<PropertyInfo> piCollection =
                poco.GetType().GetProperties()
                .Where(x => x.PropertyType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(x.PropertyType));

            foreach (PropertyInfo item in piCollection)
            {
                PropertyInfo px = poco.GetType().GetProperty(item.Name, BindingFlags.Public | BindingFlags.Instance);

                // same property exists from dto to poco
                if (px != null)
                {
                    IList col = (IList)px.GetValue(poco, null);
                    if (col == null) continue;

                    Type dtoType = item.PropertyType.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICollection<>)).Single().GetGenericArguments()[0];

                    foreach (object elem in col)
                    {
                        db.AssignStub(elem);
                    }

                }
            }
        }
开发者ID:MichaelBuen,项目名称:DitTO,代码行数:58,代码来源:EfPoco.cs


示例10: EventRepository

        public EventRepository(DbContext context)
        {
            if (context == null)
              {
            throw new ArgumentNullException("context");
              }

              _db = context as DevAgendaCtx;
        }
开发者ID:pawlos,项目名称:devAgenda,代码行数:9,代码来源:EventRepository.cs


示例11: TestGetTheRightCopier3

 public void TestGetTheRightCopier3()
 {
     DbContext dc = new DbContext("SqlServer");
     dc.NewTransaction(delegate()
     {
         IDbBulkCopy c = dc.GetDbBulkCopy();
         Assert.IsNotNull(c);
         Assert.IsTrue(c is SqlServerBulkCopy);
     });
 }
开发者ID:991899783,项目名称:DbEntry,代码行数:10,代码来源:BulkCopyTest.cs


示例12: SEORepository

        //Ctor
        public SEORepository(DbContext _DbContext, string _TableName = "")
        {
            this.TableName = _TableName;

            if (_DbContext == null)
                throw new ArgumentNullException("DbContext");

            DbContext = _DbContext;
            DbSet = _DbContext.Set<SEO>();
        }
开发者ID:RonenZ,项目名称:EitanMVC,代码行数:11,代码来源:SEORepository.cs


示例13: BulkOperationProvider

        public BulkOperationProvider(DbContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            _context = context;

            //ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings[context.GetType().Name];
            _connectionString = context.Database.Connection.ConnectionString;
        }
开发者ID:guanzhen0406,项目名称:ZTECC,代码行数:10,代码来源:BulkOperationProvider.cs


示例14: Create

		/// <summary>
		/// Create News Media Content 
		/// </summary>
		/// <param name="newsMedia">newsMedia</param>
		/// <returns>Returns the news media content</returns>
         public NewsMedia Create(NewsMedia newsMedia)
         {
            using(var database = new DbContext(CONNECTION_NAME))
             {
                database.Set<NewsMedia>().Add(newsMedia);
                database.SaveChanges();

                return newsMedia;
             }

         }
开发者ID:bhagvank,项目名称:digital-administratione-iura,代码行数:16,代码来源:NewsMediaManagementDAC.cs


示例15: AuditLogger

        /// <summary>
        /// Initializes a new instance of the <see cref="AuditLogger"/> class.
        /// </summary>
        /// <param name="dbContext">The <see cref="DbContext"/> to create the <see cref="AuditLog"/> from.</param>
        /// <param name="configuration">The <see cref="AuditConfiguration"/> to use when creating the <see cref="AuditLog"/>.</param>
        public AuditLogger(DbContext dbContext, AuditConfiguration configuration)
        {
            if (dbContext == null)
                throw new ArgumentNullException("dbContext");

            var adapter = (IObjectContextAdapter)dbContext;
            _objectContext = adapter.ObjectContext;
            _configuration = configuration ?? AuditConfiguration.Default;

            AttachEvents();
        }
开发者ID:sbarski,项目名称:EntityFramework.Extended,代码行数:16,代码来源:AuditLogger.cs


示例16: GetCachedParameters

 public static DbParameter[] GetCachedParameters(DbContext dbContext)
 {
     if (((dbContext == null) || (dbContext.Connection == null)) || (dbContext.CurrentCommand == null))
     {
         throw new ArgumentNullException("dbContext");
     }
     if ((dbContext.CurrentCommand.CommandType != CommandType.StoredProcedure) || string.IsNullOrEmpty(dbContext.CurrentCommand.CommandText))
     {
         throw new InvalidOperationException("命令不是存储过程,或没有设置存储过程。");
     }
     return InnerGetCachedParameters(dbContext.Connection, dbContext.CurrentCommand.CommandText);
 }
开发者ID:nakijun,项目名称:FastDBEngine,代码行数:12,代码来源:DBParametersManager.cs


示例17: Select

		/// <summary>
		/// Gets the list of News Media
		/// </summary>
		/// <param name="date">created date.</param>
		/// <returns>Returns the list of List<NewsMedia>.</returns>
      	 public List<NewsMedia> Select(DateTime date)
        {
            using (var database = new DbContext(CONNECTION_NAME))
             {
                 IQueryable<NewsMedia> query = database.Set<NewsMedia>();

                 query = AppendFilters(query,date);

                 return query.ToList();
             }

        }
开发者ID:bhagvank,项目名称:digital-administratione-iura,代码行数:17,代码来源:NewsPortalDAC.cs


示例18: OnBeforeSaveChanges

		public virtual void OnBeforeSaveChanges(DbContext context)
		{
			foreach (var entry in context.GetDbStateEntries())
			{
				var type = entry.Entity.GetType();
				foreach (var complexProperty in GetComplexProperties(type))
				{
					// instantiate complex type if null
					object currentValue = complexProperty.Key.GetValue(entry.Entity, new object[0]);
					object newValue = currentValue == null ? complexProperty.Value() : null;
					OnInitializeComplexType(complexProperty.Key, entry, currentValue, newValue);
				}
			}
		}
开发者ID:fjdiazt,项目名称:EntityFramework.Injection,代码行数:14,代码来源:ComplexTypeInitializationInjection.cs


示例19: SubmitChangesAsync

        /// <summary>
        /// Submits the change through Entity Framework while logging any exceptions
        /// and produce appropriate <see cref="HttpResponseMessage"/> instances.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the operation.</returns>
        public static async Task<int> SubmitChangesAsync(DbContext context, HttpRequestMessage request, Func<DbUpdateConcurrencyException, object> getOriginalValue)
        {
            HttpConfiguration config = request.GetConfiguration();
            ITraceWriter traceWriter = config.Services.GetTraceWriter();
            try
            {
                int result = await context.SaveChangesAsync();
                return result;
            }
            catch (DbEntityValidationException ex)
            {
                string validationDescription = EntityUtils.GetValidationDescription(ex);
                string validationError = EFResources.DomainManager_ValidationError.FormatForUser(validationDescription);
                traceWriter.Debug(validationError, request, LogCategories.TableControllers);
                HttpResponseMessage invalid = request.CreateErrorResponse(HttpStatusCode.BadRequest, validationError, ex);
                throw new HttpResponseException(invalid);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                string conflictError = EFResources.DomainManager_ChangeConflict.FormatForUser(ex.Message);
                traceWriter.Info(conflictError, request, LogCategories.TableControllers);

                var content = getOriginalValue != null ? getOriginalValue(ex) : conflictError;
                HttpStatusCode statusCode = GetConflictStatusCode(request);
                HttpResponseMessage conflict = request.CreateResponse(statusCode, content);
                throw new HttpResponseException(conflict);
            }
            catch (DbUpdateException ex)
            {
                HttpResponseMessage error;
                Exception baseEx = ex.GetBaseException();
                SqlException sqlException = baseEx as SqlException;
                if (sqlException != null && sqlException.Number == SqlUniqueConstraintViolationError)
                {
                    string message = CommonResources.DomainManager_Conflict.FormatForUser(sqlException.Message);
                    error = request.CreateErrorResponse(HttpStatusCode.Conflict, message);
                    traceWriter.Info(message, request, LogCategories.TableControllers);
                }
                else
                {
                    string message = EFResources.DomainManager_InvalidOperation.FormatForUser(baseEx.Message);
                    error = request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
                    traceWriter.Error(message, request, LogCategories.TableControllers);
                }

                throw new HttpResponseException(error);
            }
        }
开发者ID:RossMerr,项目名称:azure-mobile-apps-net-server,代码行数:53,代码来源:EntityUtils.cs


示例20: SqlQueryForDataTatable

 /// <summary>
 /// 通过EF执行sql语句获得Table
 /// </summary>
 /// <param name="db">数据库上下文</param>
 /// <param name="sql">sql语句</param>
 /// <returns></returns>
 public static DataTable SqlQueryForDataTatable(DbContext db,
 string sql)
 {
     SqlConnection conn = new System.Data.SqlClient.SqlConnection();
     conn.ConnectionString = db.Database.Connection.ConnectionString;
     if (conn.State != ConnectionState.Open) {
         conn.Open();
     }
     SqlCommand cmd = new SqlCommand();
     cmd.Connection = conn;
     cmd.CommandText = sql;
     SqlDataAdapter adapter = new SqlDataAdapter(cmd);
     DataTable table = new DataTable();
     adapter.Fill(table);
     return table;
 }
开发者ID:zuifengke,项目名称:windy-authordesign,代码行数:22,代码来源:EFSqlHelper.cs



注:本文中的System.Data.DbContext类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Data.ForeignKeyConstraint类代码示例发布时间:2022-05-26
下一篇:
C# Data.DataView类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap