EF状态跟踪测试

[TestClass]
public class EFTest
{
// 测试EntityKey, EntityState, ObjectContext
// 1. Detach后EntityKey是否存在? 是
// 2. EntityKey占多大内存? 小
// 3. Entity所依附的ObjectContext被Dispose后,EntityState是否自动变为Detached? 否
// 4. 当MergeOption为NoTracking时,Entity中属性的改变是否会被跟踪? 不会,为Detached状态
// 4. Entity所依附的ObjectContext被Dispose后,Entity中属性的改变是否会被跟踪?
[TestMethod]
public void trackTest()
{
int id = 5 ;
FinanceContext context
= new FinanceContext();
// DataContext在默认情况下的行为
BusinessApplication entity = context.BusinessApplication.Where(b => b.Id == id).Single();
Assert.AreEqual(EntityState.Unchanged, entity.EntityState);
entity.Title
= " 改变一下 " ;
Assert.AreEqual(EntityState.Modified, entity.EntityState);
context.Detach(entity);
Assert.IsNotNull(entity.EntityKey);
// 在DataContext Dispose以后的行为
entity = context.BusinessApplication.Where(b => b.Id == id).Single();
context.Dispose();
Assert.AreEqual(EntityState.Unchanged, entity.EntityState);
entity.Title
= " 改变一下 " ;
Assert.AreEqual(EntityState.Modified, entity.EntityState);

// DataContext当MergeOption.NoTracking时的行为
context = new FinanceContext();
entity
= null ;
context.BusinessApplication.MergeOption
= MergeOption.NoTracking;
entity
= context.BusinessApplication.Where(b => b.Id == id).Single();
Assert.AreEqual(EntityState.Detached, entity.EntityState);
entity.Title
= " 改变一下 " ;
Assert.AreEqual(EntityState.Detached, entity.EntityState);
context.Dispose();

// DataContext当MergeOption.OverwriteChanges时的行为
context = new FinanceContext();
entity
= null ;
context.BusinessApplication.MergeOption
= MergeOption.OverwriteChanges;
entity
= context.BusinessApplication.Where(b => b.Id == id).Single();
Assert.AreEqual(EntityState.Unchanged, entity.EntityState);
entity.Title
= " 改变一下 " ;
Assert.AreEqual(EntityState.Modified, entity.EntityState);
context.Dispose();

}
}

版权所有:基础软件工作室。作者:孙继磊。邮箱:[email protected]
本文首发于 http://www.cnblogs.com/FoundationSoft。文章转载请保持此版权信息并注明出处。

你可能感兴趣的:(测试)