Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using (var ctx = new EntityContext())
- {
- var newCustomer = new Customer
- {
- Description = "test",
- Name = "SOTest",
- IsActive = true
- };
- ctx.Customers.Add(newCustomer);
- ctx.SaveChanges();
- var customerID = newCustomer.CustomerID;
- var customer = ctx.Customers
- .AsNoTracking()
- .Where(x => x.CustomerID == customerID)
- .Select(x => x)
- .FirstOrDefault();
- customer.Description = "Some nasty ass description";
- ctx.ClearCache();
- ctx.Entry(customer).State = EntityState.Modified;
- ctx.SaveChanges();
- var anotherCustomer = ctx.Customers
- .AsNoTracking()
- .Where(x => x.CustomerID == customerID)
- .Select(x => x)
- .FirstOrDefault();
- anotherCustomer.Name = "Trying once more";
- //ctx.ClearCache();
- ctx.Entry(anotherCustomer).State = EntityState.Modified;
- ctx.SaveChanges();
- }
- public class Customer
- {
- public int CustomerID { get; set; }
- public string Name { get; set; }
- public string Description { get; set; }
- public Boolean IsActive { get; set; }
- }
- public class EntityContext : DbContext
- {
- public EntityContext() : base("DefaultConnectionString")
- {
- InitContext();
- }
- void InitContext()
- {
- /// Should be enabled by default, if optimization is needed then turn it off.
- Configuration.AutoDetectChangesEnabled = true;
- /// We do not use proxies for lazy loading nor change-tracking.
- Configuration.ProxyCreationEnabled = false;
- /// Should always be false!
- Configuration.LazyLoadingEnabled = false;
- ///We set this to true to avoid unnecessary check in SQL
- ///(if sending null parameter to query, SQL will check if column is null and parameter is null and we do not use this kind of filtering)
- Configuration.UseDatabaseNullSemantics = true;
- //Default timeout for connection
- Database.CommandTimeout = 60;
- }
- public void ClearCache()
- {
- Configuration.AutoDetectChangesEnabled = false;
- var trackedItems = ChangeTracker.Entries().ToList();
- foreach (var item in trackedItems)
- {
- Entry(item.Entity).State = System.Data.Entity.EntityState.Detached;
- }
- Configuration.AutoDetectChangesEnabled = true;
- }
- public DbSet<Customer> Customers { get; set; }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement