本文整理汇总了C#中System.Data.DbContext类的典型用法代码示例。如果您正苦于以下问题:C# DbContext类的具体用法?C# DbContext怎么用?C# DbContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DbContext类属于System.Data命名空间,在下文中一共展示了DbContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
示例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;
}
}
示例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
};
}
示例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;
}
示例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;
}
}
}
示例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);
}
示例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);
}
示例8: OperationRepository
public OperationRepository(DbContext context)
{
if (context == null)
{
throw new ArgumentNullException("context", "DbContext should not be empty");
}
Context = context;
}
示例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);
}
}
}
}
示例10: EventRepository
public EventRepository(DbContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
_db = context as DevAgendaCtx;
}
示例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);
});
}
示例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>();
}
示例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;
}
示例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;
}
}
示例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();
}