Last active
December 17, 2015 14:39
-
-
Save jwChung/5626059 to your computer and use it in GitHub Desktop.
EF question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class QueryingFindingEntities | |
{ | |
[Fact] | |
public void FindingEntityByPrimaryKey() | |
{ | |
using (var context = new BlogContext()) | |
{ | |
int execuedCount = 0; | |
context.RegisterCallbackStateChanged(ConnectionState.Open, () => execuedCount++); | |
context.Blogs.Find(2); | |
Assert.Equal(1, execuedCount); | |
context.Blogs.Find(2); | |
Assert.Equal(1, execuedCount); | |
context.Blogs.Add(new Blog { BlogId = -1 }); | |
context.Blogs.Find(-1); | |
Assert.Equal(1, execuedCount); | |
context.Users.Find("johndoe1987"); | |
Assert.Equal(2, execuedCount); | |
} | |
} | |
} | |
public static class DbContextExtensions | |
{ | |
public static void RegisterCallbackStateChanged(this DbContext context, ConnectionState connectionState, Action action) | |
{ | |
if (context == null) | |
{ | |
throw new ArgumentNullException("context"); | |
} | |
if (action == null) | |
{ | |
throw new ArgumentNullException("action"); | |
} | |
// 명시적으로 호출하여 초기 유효성 검증 sql실행을 counting에서 제외. | |
context.Database.Initialize(false); | |
context.Database.Connection.StateChange += (s, a) => | |
{ | |
if (connectionState == a.CurrentState) | |
{ | |
action(); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment