Skip to content

Instantly share code, notes, and snippets.

@wellwind
Last active June 22, 2017 06:56
Show Gist options
  • Save wellwind/1689eadc091a556ca57f96186dca5f5b to your computer and use it in GitHub Desktop.
Save wellwind/1689eadc091a556ca57f96186dca5f5b to your computer and use it in GitHub Desktop.
NSubstitute模擬Entity Framework的DbContext用的Extension
public static class DbContextExtensions
{
/// <summary>
/// 從ScenarioContext中取得IDbSet&lt;T&gt;,並加入dbContext中。
/// 其中propertyName若不指定則預設用T的名稱。
/// ex1: IDbSet&lt;SomeClass&gt; SomeClass
/// 在不指定propertyName時會將內容加入dbContext.SomeClass中。
/// ex2: IDbSet&lt;SomeClass&gt; AnotherName
/// 若需要使用dbContext.AnotherName則必須將propertyName設為"AnotherName"。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbContext">來源DbContext</param>
/// <param name="scenarioContextName">IDbSet&lt;T&gt;再ScenarioContext中的名稱.</param>
/// <param name="propertyName">DbContext的Property名稱.</param>
public static void SetDbSetStubFromScenario<T>(this DbContext dbContext, string scenarioContextName, string propertyName = "") where T : class
{
var dbSet = ScenarioContext.Current.Get<IDbSet<T>>(scenarioContextName);
dbContext.Set<T>().Returns(dbSet);
if (String.IsNullOrEmpty(propertyName))
{
propertyName = typeof(T).Name;
}
var dbContextType = dbContext.GetType();
var templatePropertyInfo = dbContextType.GetProperty(propertyName);
templatePropertyInfo.SetValue(dbContext, dbSet, null);
}
/// <summary>
/// 將IDbSet&lt;T&gt;加入dbContext中。
/// 其中propertyName若不指定則預設用T的名稱。
/// ex1: IDbSet&lt;SomeClass&gt; SomeClass
/// 在不指定propertyName時會將內容加入dbContext.SomeClass中。
/// ex2: IDbSet&lt;SomeClass&gt; AnotherName
/// 若需要使用dbContext.AnotherName則必須將propertyName設為"AnotherName"。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbContext">The database context.</param>
/// <param name="dbSetStub">The database set stub.</param>
/// <param name="propertyName">Name of the property.</param>
public static void SetDbSetStub<T>(this DbContext dbContext, IDbSet<T> dbSetStub, string propertyName = "")
where T : class
{
dbContext.Set<T>().Returns(dbSetStub);
if (String.IsNullOrEmpty(propertyName))
{
propertyName = typeof(T).Name;
}
var dbContextType = dbContext.GetType();
var templatePropertyInfo = dbContextType.GetProperty(propertyName);
templatePropertyInfo.SetValue(dbContext, dbSetStub, null);
}
}
public static class DbSetExtensions
{
public static IDbSet<T> Initialize<T>(this IDbSet<T> dbSet, IQueryable<T> data) where T : class
{
dbSet.Provider.Returns(data.Provider);
dbSet.Expression.Returns(data.Expression);
dbSet.ElementType.Returns(data.ElementType);
dbSet.GetEnumerator().Returns(data.GetEnumerator());
return dbSet;
}
}
@ZhaoRd
Copy link

ZhaoRd commented Jun 22, 2017

How Can I Use ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment