Quantcast
Channel: Effort - Entity Framework Unit Testing Tool
Viewing all 111 articles
Browse latest View live

New Post: Effort.EF6 with MigrateDatabaseToLatestVersion

$
0
0
Hi!

Is it possible to use effort with MigrateDatabaseToLatestVersion database Initializer?
I have a project which use it with initializer defined like this:
        static LibraryContext()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<LibraryContext, Configuration>());
        }
Problem is that effort can't initialize the dabase:
Test Name: GetBook_WithNonExistingId_ReturnsNull
Test FullName: Testy_Jednostkowe.BookRepositoryTests.GetBook_WithNonExistingId_ReturnsNull
Test Source: d:\documents\visual studio 2015\Projects\Testowanie_EF6_Wlaczone_Migracje\Testy_Jednostkowe\BookRepositoryTests.cs : line 28
Test Outcome: Failed
Test Duration: 0:00:04,6449765

Result StackTrace:
w Effort.Internal.DbManagement.DbContainer.get_Internal()
w Effort.Internal.DbManagement.DbContainer.GetTable(String name)
w Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbScanExpression expression)
w System.Data.Entity.Core.Common.CommandTrees.DbScanExpression.Accept[TResultType](DbExpressionVisitor1 visitor)
w Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbExpression expression)
w Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbFilterExpression expression)
w System.Data.Entity.Core.Common.CommandTrees.DbFilterExpression.Accept[TResultType](DbExpressionVisitor
1 visitor)
w Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbExpression expression)
w Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbLimitExpression expression)
w System.Data.Entity.Core.Common.CommandTrees.DbLimitExpression.Accept[TResultType](DbExpressionVisitor1 visitor)
w Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbExpression expression)
w Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbProjectExpression expression)
w System.Data.Entity.Core.Common.CommandTrees.DbProjectExpression.Accept[TResultType](DbExpressionVisitor
1 visitor)
w Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbExpression expression)
w Effort.Internal.CommandActions.QueryCommandAction.ExecuteDataReader(ActionContext context)
w Effort.Provider.EffortEntityCommand.ExecuteDbDataReader(CommandBehavior behavior)
w System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
w System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()
w System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TInterceptionContext,TResult](Func1 operation, TInterceptionContext interceptionContext, Action1 executing, Action1 executed)
w System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
w System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
w System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
w System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
--- End of inner exception stack trace ---
w System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
w System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
w System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass3.<GetResults>b__2()
w System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func
1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
w System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass3.<GetResults>b__1()
w System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func
1 operation)
w System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)
w System.Data.Entity.Core.Objects.ObjectQuery1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
w System.Lazy
1.CreateValue()
w System.Lazy1.LazyInitValue()
w System.Lazy
1.get_Value()
w System.Data.Entity.Internal.LazyEnumerator1.MoveNext()
w System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable
1 source)
w System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable1 sequence)
w System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable
1 query, Expression queryRoot)
w System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
w System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
w System.Linq.Queryable.SingleOrDefault[TSource](IQueryable1 source, Expression1 predicate)
w Baza.BookRepository.Get(Int32 id) w d:\documents\visual studio 2015\Projects\Testowanie_EF6_Wlaczone_Migracje\Baza\BookRepository.cs:wiersz 16
w Testy_Jednostkowe.BookRepositoryTests.GetBook_WithNonExistingId_ReturnsNull() w d:\documents\visual studio 2015\Projects\Testowanie_EF6_Wlaczone_Migracje\Testy_Jednostkowe\BookRepositoryTests.cs:wiersz 33
Result Message:
Test method Testy_Jednostkowe.BookRepositoryTests.GetBook_WithNonExistingId_ReturnsNull threw exception:
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> Effort.Exceptions.EffortException: Database has not been initialized.

If using CodeFirst try to add the following line:
context.Database.CreateIfNotExists()

New Post: CSV Loader Cannot Handle Nullable Ints

$
0
0
I had a few teething issues with setting up the CSV data loader for my tests. Chief among these was that SQL Server handles booleans as a bit data type, which means that upon export, I have to go and manually edit all of the boolean fields to "true" or "false" in place or 1 or 0. This is mostly just an inconvenience though, as I could build a query to generate the correct text values for any required bulk data import.

The bigger problem I found, though, was in how nullable integer types are handled. For a long time, my CSV was failing to import due to a mysterious "Input not in correct format" exception. I could see in the stack trace that the root cause of the problem was in a call to Int32.Parse(). In the end I found that the import could only be made to work if I supplied integer values for all of the cells in a column that was supposed to map to a nullable int property (unfortunately whoever designed my enterprise database appears to have been obsessed with nullable fields).

This is incredibly unfortunate, as it would obviously make it impossible for me to test scenarios in my DAL involving null values. I'm curious if there's some deeper issue behind this limitation, or whether it's just an oversight.

Commented Unassigned: Nested Any [735]

$
0
0
I have a pair of tables, with a 1-many relationship, and a FK defined. The model has navigational properties defined, child.parent and parent.children.

What works, against SQL Server, and doesn't seem to, in Effort:

```
var result = myDbContext.parents
.Where(p => p.name == "SMITH")
.Where(p => p.children.Any(c => c.age == 10)
```
Comments: I have a very similar problem. If I use the lambda .Where(crs => crs.Element.MainElementId == _Id) it does not work in the unit test but works perfectly with SQLServer. Weird thing is that when I filter on the primary key I do not get an exception: .Where(crs => crs.Element.Id == _Id) The transaction will abort after about 10 seconds: Test Name: CheckUpdateAndPublishClassroomSession Test FullName: Business.Write.Tests.LearningPaths.Elements.ClassroomSessionTransactionTest.CheckUpdateAndPublishClassroomSession Test Source: C:\development\Rushmore\dev-2009\Learnlinq\Business.Write.Tests\Transactions\LearningPath\Elements\ClassroomSessionElementTransactionTest.cs : line 276 Test Outcome: Failed Test Duration: 0:00:18,6312279 Result StackTrace: bij NMemory.Transactions.Transaction.EnsureTransaction(Transaction& transaction, IDatabase database) bij NMemory.Tables.Table`2.Update(IQueryable`1 query, IUpdater`1 updater, Transaction transaction) bij NMemory.Tables.Table`2.NMemory.Tables.IBulkTable<TEntity>.Update(TableQuery`1 query, Expression`1 updater, Transaction transaction) bij NMemory.Linq.QueryableEx.Update[T](IQueryable`1 queryable, Expression`1 updater, Transaction transaction) bij Effort.Internal.Common.DatabaseReflectionHelper.WrapperMethods.UpdateEntities[TEntity](IQueryable`1 query, Expression`1 updater, Transaction transaction) --- End of inner exception stack trace --- bij System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) bij System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) bij System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) bij Effort.Internal.Common.DatabaseReflectionHelper.UpdateEntities(IQueryable source, Expression updater, Transaction transaction) bij Effort.Internal.CommandActions.UpdateCommandAction.ExecuteNonQuery(ActionContext context) bij Effort.Provider.EffortEntityCommand.ExecuteNonQuery() bij System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c) bij System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) bij System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext) bij System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery() bij System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues) bij System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() --- End of inner exception stack trace --- bij System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() bij System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut) bij System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction) bij System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() bij System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35() bij System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) bij System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) bij System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27() bij System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation) bij System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) bij System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) bij System.Data.Entity.Internal.InternalContext.SaveChanges() --- End of inner exception stack trace --- bij System.Data.Entity.Internal.InternalContext.SaveChanges() bij System.Data.Entity.Internal.LazyInternalContext.SaveChanges() bij System.Data.Entity.DbContext.SaveChanges() bij Learnlinq.Data.Core.DataAccess.DataContextBase.SaveChanges() Result Message: Test method Business.Write.Tests.LearningPaths.Elements.ClassroomSessionTransactionTest.CheckUpdateAndPublishClassroomSession threw exception: System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Reflection.TargetInvocationException: Het doel van een aanroep heeft een uitzondering veroorzaakt. ---> System.Transactions.TransactionAbortedException: De transactie is afgebroken.

Commented Unassigned: Using Migrations with Effort [765]

$
0
0
When I try to create a new DBContext, EF6 complains that "Migrations is Enabled" for the context. How can I force the context to be created without caring about migrations for testing?
Comments: Hi - Please check this similar ticket: https://github.com/tamasflamich/effort/issues/26

Closed Unassigned: Using Migrations with Effort [765]

$
0
0
When I try to create a new DBContext, EF6 complains that "Migrations is Enabled" for the context. How can I force the context to be created without caring about migrations for testing?
Comments: wontfix

Updated Wiki: Home

$
0
0

Overview

Effort is a powerful tool that enables a convenient way to create automated tests for Entity Framework based applications.
It is basically an ADO.NET provider that executes all the data operations on a lightweight in-process main memory database instead of a traditional external database. It provides some intuitive helper methods too that make really easy to use this provider with existing ObjectContext or DbContext classes. A simple addition to existing code might be enough to create data driven tests that can run without the presence of the external database.

Contribution & bug reports

Please use the Github project page.

Getting started

Updated Wiki: NuGet Packages

$
0
0

Packages

If you use Entity Framework 6...

  • You will need the Effort.EF6 package
  • Check the offical NuGet site

otherwise...

  • You will need the Effort package
  • Check the offical NuGet site

Installation

 

New Post: Using Effort and getting "The transaction has aborted" error

$
0
0
Hi

I am trying to use Effort for integration testing and I am seeing a DbUpdateExcpetion thrown. When I get to the inner most exception, I see: "transaction is aborted. The code works fine when I use the local sql db. Here is the code and stack trace. The issue happens in the method InsertAndGetDbFeatureAsync(featureStoreContext, feature.Id); when it is called for the second time in the for loop.
    public async Task AddFeatureFileAsync(IngestionFeatureFile ingestionFeatureFile, IngestionBuildInfo buildInfo, IFeatureStoreDependencyManager dependencyManager)
    {
        await ExecutionHelper.ExecuteTransactionWithRetryAsync(async () =>
        {
            using (var featureStoreContext = (FeatureStoreContext)this.contextFactory.Create())
            {
                using (var dbContextTransaction = featureStoreContext.Database.BeginTransaction())
                {
                    try
                    {
                        var dbFeatureGroupInfos = new List<DbFeatureGroupInfo>();
                        foreach (var featureGroup in ingestionFeatureFile.IngestionFeatureGroups)
                        {

                            var dbFeatureInfos = new List<DbFeatureInfo>();
                            foreach (var feature in featureGroup.ChildFeatures)
                            {
                                DbFeature dbFeature = await InsertAndGetDbFeatureAsync(featureStoreContext, feature.Id);
                                DbFeatureInfo dbFeatureInfo = await InsertFeatureInfoIfNewAsync(featureStoreContext, feature, dbFeature);

                                dependencyManager.SaveDbFeatureInfo(feature.ClassName, dbFeatureInfo.Id);
                                dependencyManager.SaveDbFeatureInfo(feature.Id, dbFeatureInfo.Id);

                                dbFeatureInfos.Add(dbFeatureInfo);
                            }

                            DbFeatureGroupInfo dbFeatureGroupInfo = await InsertFeatureGroupInfoIfNewAsync(featureStoreContext, featureGroup, dbFeatureInfos);
                            dbFeatureGroupInfos.Add(dbFeatureGroupInfo);
                        }

                        DbFeatureFileInfo dbFeatureFileInfo = await InsertDbFeatureFileInfoIfNewAsync(featureStoreContext, ingestionFeatureFile, dbFeatureGroupInfos);
                        await InsertDbBuildInfoIfFileNewInBranchAsync(featureStoreContext, buildInfo, dbFeatureFileInfo);

                        dbContextTransaction.Commit();
                    }
                    catch (Exception)
                    {
                       dbContextTransaction.Rollback();
                        throw;
                    }
                }
            }
        });
    }

    private static async Task<DbFeature> InsertAndGetDbFeatureAsync(FeatureStoreContext featureStoreContext, int featureId)
    {
        DbFeature dbFeature = await featureStoreContext.DbFeatures.SingleOrDefaultAsync(f => (f.DbFeatureId == featureId));

        if (dbFeature == null)
        {
            dbFeature = new DbFeature
            {
                DbFeatureId = featureId
            };

            featureStoreContext.DbFeatures.Add(dbFeature);
            await featureStoreContext.SaveChangesAsync();
        }

        return dbFeature;
    }
Stack trace:
System.Data.Entity.Infrastructure.DbUpdateException occurred
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=mscorlib
StackTrace:
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Velocity.Internal.FeatureStoreIngestionManager.<InsertAndGetDbFeatureAsync>d__9.MoveNext() in e:\velocity6\VelocityServiceV1\Shared\FeatureStoreModel\FeatureStoreManager\FeatureStoreIngestionManager.cs:line 148
InnerException:
   HResult=-2146233087
   Message=An error occurred while updating the entries. See the inner exception for details.
   Source=EntityFramework
   StackTrace:
        at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.<UpdateAsync>d__0.MoveNext()
     --- End of stack trace from previous location where exception was thrown ---
        at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
        at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        at System.Data.Entity.Core.Objects.ObjectContext.<ExecuteInTransactionAsync>d__3d`1.MoveNext()
     --- End of stack trace from previous location where exception was thrown ---
        at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
        at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStoreAsync>d__39.MoveNext()
     --- End of stack trace from previous location where exception was thrown ---
        at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
        at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesInternalAsync>d__31.MoveNext()
   InnerException: 
        HResult=-2146232828
        Message=Exception has been thrown by the target of an invocation.
        Source=mscorlib
        StackTrace:
             at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
             at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
             at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
             at Effort.Internal.Common.DatabaseReflectionHelper.InsertEntity(ITable table, Object entity, Transaction transaction)
             at Effort.Internal.CommandActions.InsertCommandAction.CreateAndInsertEntity(ITable table, IList`1 memberBindings, Transaction transaction)
             at Effort.Internal.CommandActions.InsertCommandAction.ExecuteNonQuery(ActionContext context)
             at Effort.Provider.EffortEntityCommand.ExecuteNonQuery()
             at System.Data.Common.DbCommand.ExecuteNonQueryAsync(CancellationToken cancellationToken)
          --- End of stack trace from previous location where exception was thrown ---
             at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
             at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
             at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult()
             at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.<ExecuteAsync>d__0.MoveNext()
          --- End of stack trace from previous location where exception was thrown ---
             at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
             at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
             at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.<UpdateAsync>d__0.MoveNext()
        InnerException: 
             HResult=-2146233087
             Message=The transaction has aborted.
             Source=NMemory
             StackTrace:
                  at NMemory.Transactions.Transaction.EnsureTransaction(Transaction& transaction, IDatabase database)
                  at NMemory.Tables.Table`2.Insert(TEntity entity, Transaction transaction)
                  at Effort.Internal.Common.DatabaseReflectionHelper.WrapperMethods.InsertEntity[TEntity](ITable`1 table, TEntity entity, Transaction transaction)
             InnerException: 

New Post: Will Effort be made for EF Core?

New Post: Performance (RAM/CPU) with a lot of includes

$
0
0
Hello, anybody using Effort with big linked tables?

We are currently using a statment to eager load a big amount of data (its not big per table but its linked a lot)

we have maybe 20-30 includes in the query.

in the tables there is not much more than 100-200 rows atm

Effort uses with this settinfs up to 2,5 GB (!) of memory and takes about 3 min to finish

The database enigine (localdb and oracle) deliver in < 3seconds

Am i doing something wrong or is effort just not optimized for such scenarios ?

New Post: Persistent Connection - Is there a way to wipe it?

$
0
0
We're trying to use the persistent connection in some specflow automated tests, which works great! However, we're facing some problems when we run multiple features on the same test run. Is there a way to clear the data on a persistent connection?

Certainly we could use different connection ids on each test, but that's not pretty scalable.

Thank you.

New Post: Using Effort along with real intergration tests

$
0
0
In my project I use 2 kinds of test:
1 with real connection to the database.
  System.Data.Entity.Database.SetInitializer(new ContextInitializer());
   ...
2 Effort tests

And because of that, when I run both at once, the Effort tests fail on
Effort.EntityConnectionFactory.CreateTransient
But if I run them separately, for example, real test then effort tests, they work well.

Is there any way to fix it?

New Post: Using connection string

$
0
0
Hi

In the project I am working on we have built a repository system using entity framework. However we pass in the connection string to create the dbcontexts as our system connects to databases depending on the account using the system.

I can get effort to create a db in memory following the tutorials but when trying to use the connection string on the created db I just get "Keyword not supported: 'instanceid'." ie the effort db does not have a connection string that the dbcontext can use as a connection string.

I have at one part made it possible to pass through the DbConnection but this makes my production code messy as means that checks need to be made if when running the test it is a test, which in my mind is wrong.

I am wondering if there is any way of getting a full connection string on a Effort created db so that dbcontext can use it as a connection string?

Thanks

Dusty

New Post: Effort with BulkInsert

$
0
0
Hi,

I am trying to implement Effort in a EF 6.0 + MS SQL Server context. I am also trying to take advantage on the existing logic to insert the data in the database: mainly based on BulkInsert. I am having troubles with it, as part of its implementation relies on the following method:
    private static string GetTableName<TEntity>(this DataContext context) where TEntity : class, IEntity
    {
        var sql = context.Set<TEntity>().ToString();
        var regex = new Regex("FROM (?<Table>.*) AS");
        var match = regex.Match(sql);

        return match.Groups["Table"].Value;
    }
The sql variable is always null, and this causes a chain of errors which make impossible to finally execute the bulk insert. I believe that this error is caused by Effort's specificity, after all, it only abstractise the DbContext, so not all the things that worked in a EF environment would work on the Effort environment.

As far as I've seen, Effort uses csv imports in order to initialize the data: is this the right way to deal with these massive data initialisation imports? Has anyone succeeded to implement a BulkInsert with Effort?

I might also add that currently I am initialise the data with normal Add() commands, which takes a lot of time: If Effort employs in-memory data structures, why does it take so long for the saves to be done?

Kind regards,
C.

New Post: Test transaction rollback

$
0
0
Hi,
I am using effort framework to test entity framework using Microsoft Unit testing framework. I am trying to test rolling back a transaction. The test code is

public void TestTransactionRollBack(){
  DbContext db = new DbContext();
  LoadData() // this method populates the tables in the memory database
  using (var trans = db.Database.BeginTransaction()){
      var result = db.MyTable.Find(1);
      result.DateChanged = null;
      db.SaveChanges();
      trans.RollBack();
  }     
  var result1 = db.MyTable.Find(1);
  Assert.IsNotNull(result1.DateChanged); //Assertion fails
}

Could you please suggest how to test if the changes were rolled back or not.

Thank you

New Post: The Effort library failed to register its provider automatically

$
0
0
OVERVIEW
Using Fitnesse with EF6, can't get Effort to start up.
I've tried every trick in all the posts I can find.

So far,
I have "Effort.Provider" in the DbProviderFactories section in machine.config.
I have Effort.Provider showing up when I look at DbProviderFactories.GetFactoryClasses();
ProcMon shows that it is looking for and finding Effort.dll.

Also tried,
"Effort.Provider" in the entityFramework section of Runner.exe.config but couldn't get that to work. Just crashed the app.
Uninstalling EF and Effort.EF6 and re-installing. No visible effect.
Calling Effort.Provider.EffortProviderConfiguration.RegisterProvider(); from a class constructor and various startup locations. Effort.Provider never showed up in DbProviderFactories.GetFactoryClasses();
"Effort.Provider" in the DbProviderFactories section in app.config. It shows up in GetFactoryClasses just as well as machine.config.

Result,
Any of
DbConnectionFactory.CreateTransient();
Effort.EntityConnectionFactory.CreateTransient(connectionString);
DbProviderFactory dataFactory = DbProviderFactories.GetFactory(dt.Rows[5]);
throw
Effort.Exceptions.EffortException: The Effort library failed to register

Using
Windows 10
.Net 4.6
VS 2016
EF 6.1.2 (although it says 6.1.3 is installed, not sure what that means)

Do I need to register a DLL or something?

Details,
App.config
<configuration>
<runtime>
    <loadFromRemoteSources enabled="true"/>
</runtime>
<system.data>
    <DbProviderFactories>
        <add name="Effort.Provider" invariant="Effort.Provider" description="Effort.Provider" type="Effort.Provider.EffortProviderFactory, Effort" />
    </DbProviderFactories>
</system.data>
</configuration>

New Comment on "Create a fake DbContext instance"

$
0
0
@jdege: Copy/paste the connection string that is in your App.config file. Paste this into the argument for CreateTransient() in the code above. This should be the connection string that starts with "metadata=res://*/BlahBlah.csdl|..." You will also need to turn the &quot; tokens into actual single quotes. After I did this I was able to get the sample to work using EF6, "Effort.EF6" library from nuget (as distinct from "Effort" without the EF6) and using a Database First approach.

New Post: Unit Tests - Attempted to read or write protected memory - System.AccessViolation

$
0
0
We recently started playing around with Effort hoping to remove our database dependencies from our unit tests, and we've just ran into this same error. For us it appears to be triggered when we have Telerik's JustMock profiler enabled. I believe it uses the .NET Profiler API to allow for more advanced mocking functions (static/concrete members, etc) , and unfortunately we have some tests that require it right now.

Did you guys ever find a solution? We're at a loss for how to make the two play nicely together - short of removing our dependence on the profiler functionality.

Commented Unassigned: Lazy Loading disabled but Effort eagerly loads all [745]

$
0
0
We have "LazyLoadingEnabled" set to false for our implementation of DbContext. I've double-checked in a production integration test and related entities are only loaded if we explicitly call an "Include". But for the unit tests using Effort, if I seed an aggregate root object with related entities, all related entities are automatically included eagerly when I pull the object back out of the context.

//-----------------------------------------------------------------

public class DataContext : DbContext, IContext {

public IDbSet<Foo> Foos { get; set; }
public IDbSet<FooInputKey> FooInputKeys { get; set; }
public IDbSet<FooInputValue> FooInputValues { get; set; }

private bool isContextUnderTest;

public DataContext()
: base("FooDatabaseProd") {
Initialize();
}

public DataContext(DbConnection connection, bool isContextUnderTest = false)
: base(connection, contextOwnsConnection: false) {

this.isContextUnderTest = isContextUnderTest;
Initialize();
}

private void Initialize() {
this.Configuration.LazyLoadingEnabled = false;
}

public void ConcludeTest() {
this.isContextUnderTest = false;
this.Dispose(true);
}

protected override void Dispose(bool disposing) {
if (!isContextUnderTest)
base.Dispose(disposing);
}
}

//-----------------------------------------------------------------

[TestClass]
public class FooControllerTests
{
private DataContext dbContext;
private Mock<IContextFactory> mockContextFactory;
private FooController fooController;

[TestInitialize]
public void Setup() {
var transientConnection = Effort.DbConnectionFactory.CreateTransient();
this.dbContext = new DataContext(transientConnection, isContextUnderTest: true);
this.mockContextFactory = new Mock<IContextFactory>();
this.mockContextFactory.Setup(ctx => ctx.CreateDataContext()).Returns(this.dbContext);
this.fooController = new FooController(this.mockContextFactory.Object);
}

[TestCleanup]
public void Teardown() {
this.dbContext.ConcludeTest();
}

[TestMethod]
public void Should_only_return_the_Foo_and_not_include_any_FooInputKeys() {
// Arrange
var fooInputKeys = new List<FooInputKey> {
new FooInputKey { Name = "Alpha" },
new FooInputKey { Name = "Beta" },
new FooInputKey { Name = "Gamma" },
};
var foo = new Foo { FooInputKeys = fooInputKeys };
this.dbContext.Foos.Add(foo);
this.dbContext.SaveChanges();

// Act
var result = this.fooController.GetFooById(foo.Id);
var fooResult = JsonConvert.DeserializeObject<Foo>(result);

// Assert -- FAILS
// Includes all 3 FooInputKeys provided. Works as intended (none provided) in production test.
fooResult.FooInputKeys.Should().BeEmpty();
}

Comments: Since Effort is mainly used in unit tests, this is massive issue. If the PROD environment has LazyLoading=false, but the unit tests has LazyLoading=true (even when set to false), then the unit tests can succeed where they should have failed, and the other way around.

Created Unassigned: Effort Test fails if we add modelBuilder configuration [766]

$
0
0
I see the tests that had been passing started to fail when I added a fluentApi configuration to process string as varchar instead of treating them as NVARCHAR.

configuration added :
modelBuilder.Properties<string>().Configure(c => c.HasColumnType("VARCHAR"));

Error: (See attached code)
Unable to create instance of class EffortTest.CatTests. Error: System.InvalidOperationException: Sequence contains no matching element.

Viewing all 111 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>