Git Product home page Git Product logo

entityframework-effort's Introduction

Library Powered By

This library is powered by Entity Framework Extensions

Entity Framework Extensions

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 also provides some intuitive helper methods that make this provider really easy to use 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 external database's presence.

NuGet:https://www.nuget.org/packages/Effort/

Useful links

Contribute

The best way to contribute is by spreading the word about the library:

  • Blog it
  • Comment it
  • Star it
  • Share it

A HUGE THANKS for your help.

More Projects

To view all our free and paid projects, visit our website ZZZ Projects.

entityframework-effort's People

Contributors

albinsunnanbo avatar alexangas avatar baderbuddy avatar bushero avatar dbeuchler avatar gius avatar jonathanmagnan avatar kubabuda avatar lempireqc avatar nielshede avatar nnordhaus avatar reduckted avatar stgelaisalex avatar tamasflamich avatar waqasm78 avatar wertzui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

entityframework-effort's Issues

Transaction aborted when using context.Database.BeginTransaction

When using this approach, the transaction commit throws:

using (var transaction = context.Database.BeginTransaction()) {

    // stuff

    transaction.Commit(); // throws
}

The exception is:

System.Data.Entity.Infrastructure.CommitFailedException : An error was reported while committing a database transaction but it could not be determined whether the transaction succeeded or failed on the database server. See the inner exception and http://go.microsoft.com/fwlink/?LinkId=313468 for more information.
  ----> System.Transactions.TransactionAbortedException : The transaction has aborted.
  ----> System.TimeoutException : Transaction Timeout

However if I use context.Database.Connection.BeginTransaction() instead, it is working:

using (var transaction = context.Database.Connection.BeginTransaction()) {

    // stuff

    transaction.Commit(); // doesn't throw
}

EDIT: Probably something else happening.

Duplicate Items or Missing Foreign Keys For String Primary Keys

Hi, having some issues with primary keys as strings which due to case insensitive nature of strings in memory getting:

MultipleUniqueKeyFoundException:

TargetSite

RuntimeMethodInfo4
UniqueHashtable<TKey,TEntity>.Insert (TKey key, TEntity entity)

StackTrace
at NMemory.DataStructures.UniqueHashtable2.Insert(TKey key, TEntity entity) at Effort.Internal.DbManagement.Engine.ExtendedTable2.Initialize(IEnumerable`1 entities)

Looks like NMemory is having some issues with strings...

Is there any way I can make Effort.EF6 work with a null database initialiser?

Hi,

I am using your excellent Effort.EF6 package in my Unit Tests. I handle database migrations myself and use a null database initialiser to stop EF checking the migrations at the start.

However, if I called Database.SetInitializer<MyDbContext>(null) in a Unit Test class (I am xUnit) then Effort throws an exception (below) and shows the message Effort.Exceptions.EffortException. Database has not been initialized.

Obviously this is an edge case, but if you have any ideas on how I might get round it I would appreciate it.

Full Exception information

System.Data.Entity.Core.EntityCommandExecutionException
An error occurred while executing the command definition. See the inner exception for details.
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
   at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   at Tests.UnitTests.Group01Tests.EffortEF6.TestEffortUsage.CreateDbContextViaEffort() in C:\Users\Jon\documents\visual studio 2015\Projects\OilAndGasWeb\Tests\UnitTests\Group01Tests\EffortEF6\TestEffortUsage.cs:line 22

Effort.Exceptions.EffortException
Database has not been initialized.

If using CodeFirst try to add the following line:
context.Database.CreateIfNotExists()
   at Effort.Internal.DbManagement.DbContainer.get_Internal()
   at Effort.Internal.DbManagement.DbContainer.GetTable(String name)
   at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbScanExpression expression)
   at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbGroupByExpression expression)
   at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbProjectExpression expression)
   at Effort.Internal.CommandActions.QueryCommandAction.ExecuteDataReader(ActionContext context)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)

Multiple includes are very slow

Hi,
We are using Effort to unit/integration test some EF6 code that usually depends on a SQL Server database.
At one point the code runs a statement similar to:

v = context.Stuff
                    .Include("Things")
                    .Include("Things.Children")
                    .Include("Table1.Nav1")
                    .Include("Table1.Nav2")
                    .Include("Table2.Nav1")
                    .Include("Table2.Nav2")
                    .FirstOrDefault(x => x.ThingId == matchObject.ThingId);

When executing against SQL Server with thousands of rows this typically takes around 1 second to execute. Using Effort with only 2 rows in the Stuff collection and nothing in the Included tables it takes about 2 minutes to execute.

This is an issue for us. Is there anything I can do to speed it up?

Can Effort not be used with Code-First?

This is more of a discussion item, but I don't really see any solid examples anywhere on how to use Effort with a code first context. I tried just creating a MyDbContext as in one of the tutorials, but none of its IDbSet<> properties get populated.

So I guess can you let me know if this is a limitation (and document it on the site) or give me a hint as to how it can be done (and document it).

I can try to help a bit with the documentation bit if I understand how this is intended to work.

Failing tests

I have a bunch of test that work with structuremap ioc in visual studio during development I use ncrunch which run my tests in the background and one at the time so far no problems. But all the tests were failing on the build server prompting me to add a line at app startup on put something something in my app.config which I have already done. After futher investigation I notice when the tests are run one at the time in test explorer they work fine but when run all test is used they all fail. I have isolated my setup in the following repo: https://github.com/wendellm/Cards could you have a look and tell me what I am dong wrong or have that I might have discovered a bug :)

Issue when using second level cache

Hey,
I've installed EF seconde level cache https://efcache.codeplex.com/ and all my unit testing failed now This is on the result stack :

Result StackTrace:  
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
   at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
   at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable`1 sequence)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
   at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
   at MyProject.Migrations.SeedData.DefaultEditionsBuilder.CreateEditions() in C:\Users\Admin\Source\Repos\project\MyProject.EntityFramework\Migrations\SeedData\DefaultEditionsBuilder.cs:line 24
   at MyProject.Migrations.SeedData.DefaultEditionsBuilder.Build() in C:\Users\Admin\Source\Repos\project\MyProject.EntityFramework\Migrations\SeedData\DefaultEditionsBuilder.cs:line 19
   at MyProject.Migrations.SeedData.InitialDataBuilder.Create() in C:\Users\Admin\Source\Repos\project\MyProject.EntityFramework\Migrations\SeedData\InitialDataBuilder.cs:line 19
   at MyProject.Tests.AppTestBase.<>c.<.ctor>b__0_0(CrmDbContext context) in C:\Users\Admin\Source\Repos\project\Tests\MyProject.Tests\AppTestBase.cs:line 36
   at MyProject.Tests.AppTestBase.UsingDbContext(Action`1 action) in C:\Users\Admin\Source\Repos\project\Tests\MyProject.Tests\AppTestBase.cs:line 70
   at MyProject.Tests.AppTestBase..ctor() in C:\Users\Admin\Source\Repos\project\Tests\MyProject.Tests\AppTestBase.cs:line 34
   at MyProject.Tests.Authorization.Users.UserAppServiceTestBase..ctor() in C:\Users\Admin\Source\Repos\project\Tests\MyProject.Tests\Authorization\Users\UserAppServiceTestBase.cs:line 9
   at MyProject.Tests.Authorization.Users.UserAppService_GetUsers_Tests..ctor()
----- Inner Stack Trace -----
   at EFCache.QueryRegistrar.ContainsQuery(MetadataWorkspace workspace, String sql)
   at EFCache.CachingCommand.get_IsQueryAlwaysCached()
   at EFCache.CachingCommand.get_IsCacheable()
   at EFCache.CachingCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
Result Message: 
System.Data.Entity.Core.EntityCommandExecutionException : An error occurred while executing the command definition. See the inner exception for details.
---- System.ArgumentNullException : Value cannot be null.
Parameter name: sql

How can I fix it please?

Read after SaveChanges does not work inside transaction

I love using Effort/NMemory for my testing, but now I ran into a problem:
When I use an explicit transaction (since I want to be able to do a rollback), the results of SaveChanges are not visible until I do a commit:

using (DbContextTransaction transaction = context.Database.BeginTransaction())
{
    // Store a recipe:
    context.Recipes.Add(recipe);
    context.SaveChanges(); // no commit!

    // Now retrieve it:
    int total = context.Recipes.Count(); // result is zero
}

This behavior is different from SQL Server, which makes newly stored rows visible inside the transaction (so the value of total would be 1). My code relies on this to check what has already been stored.

Is there anything I am doing wrong or is this a bug?

Support for same named tables across multiple schemas

I am running into an issue whereby I have two tables with the same table name, but in different schemas.
This works fine against a real database, with the only limitation being that EF require the two entity classes to have different names.

From what I can gather, Effort ends up partially merging the two table definitions together inside of Effort.Internal.DbManagement.CanonicalContainer.GetEntities().

Poking around a bit, a solution might be as simple as changing Effort.Internal.Common.EdmHelper.GetTableName() to prepend the scheama name to the table name, but I am not sure of the implications of this.

System.InvalidOperationException: Sequence contains no matching element

Just to emphasize, codeplex currently doesn't support adding new threads to issue or discussion board, otherwise I would post this issue there.

This simple test fails on any attempt to work with DbSet.

public async Task TestMethod1()
{
    DbConnection inMemoryConnection =                
        Effort.DbConnectionFactory.CreateTransient();

    using (var dbContext = MyDbContext.CreateDbContext(inMemoryConnection)) 
    {
        // Fails on this line (triggered by Add method):
        dbContext.Users.Add(new User()
        {
            Id = 1                         
        });
        var item = dbContext.User.Find(1);
        Assert.AreEqual(1, item.Id);
    } 
}

Tried Methods like Add, Find, FindAsync, linq queries, etc. Also tried with a couple of even simpler entities. Tried using IDbSet as well. Also played around with the app.config and finally removed any references to Effort from the config in regards to DB connection.

I have no idea what I'm missing... Any suggestions?

Top exception is:

_System.InvalidOperationException: Sequence contains no matching element_

Test Name:  TestMethod1
Test FullName:  ****
Test Source:    **** : line 21
Test Outcome:   Failed
Test Duration:  0:00:00,5738216

Result Message: 
Test method ****.TestMethod1 threw exception: 
System.InvalidOperationException: Sequence contains no matching element
Result StackTrace:  
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
   at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name)
   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty column, EntityType table, DbProviderManifest providerManifest)
   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty column, EntityType table, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)
   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.<>c__DisplayClass4.<Configure>b__3(Tuple`2 pm)
   at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(IEnumerable`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)
   at System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride)
   at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigurePropertyMappings(DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest, Boolean allowOverride)
   at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EntityType entityType, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
   at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, ICollection`1 entitySets, DbProviderManifest providerManifest)
   at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
   at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
   at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
   at System.Data.Entity.DbSet`1.Add(TEntity entity)
   at ****.<TestMethod1>d__1.MoveNext() in ****:line 29
--- 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.Runtime.CompilerServices.TaskAwaiter.GetResult()

Partial of the MyDbContext:

public class MyDbContext : DbContext
{    
    public DbSet<User> Users { get; set; }

    private MyDbContext() : base()
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    private MyDbContext(DbConnection connection) : base(connection, true)
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    public static MyDbContext CreateDbContext(DbConnection connection = null)
    {
        if (connection == null)
           return new MyDbContext();

        return new MyDbContext(connection);
    }
}

This is the User Entity.

public class User
{

    [Key]
    public long Id { get; set; }

    [Required]
    [MaxLength(PropertyLengths.UserUsernameMax)]
    [MinLength(PropertyLengths.UserUsernameMin)]
    [Index(IsUnique = true)]
    public string Username { get; set; }

    [Required]
    [MaxLength(PropertyLengths.UserEmailMax)]
    [EmailAddress]
    [Index(IsUnique = true)]
    public string Email { get; set; }

    public DateTime RegistrationTime { get; set; }

    [Required]
    [MaxLength(PropertyLengths.UserPasswordBinaryMax)]
    public byte[] Password { get; set; }

    public bool IsSupaUza { get; set; }

    public virtual ICollection<SomeEntity1> SomeEntities1 { get; set; }

    public virtual ICollection<SomeEntity2> SomeEntities2 { get; set; }

    public virtual ICollection<SomeEntity3> SomeEntities3 { get; set; }

    [MaxLength(PropertyLengths.DefaultMax)]
    public string FirstName { get; set; }

    [MaxLength(PropertyLengths.DefaultMax)]
    public string LastName { get; set; }

    [Column(TypeName = "Date")]
    public DateTime DateOfBirth { get; set; }

    [MaxLength(PropertyLengths.BlobUri)]
    public string MyCoolPic { get; set; }     
}

Unit test project app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />      
    </providers>
  </entityFramework>  
</configuration>

Unit test project packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Effort.EF6" version="1.1.4" targetFramework="net45" />
  <package id="EntityFramework" version="6.1.3" targetFramework="net45" />
  <package id="NMemory" version="1.0.1" targetFramework="net45" />
</packages>

Effort.EF6 with MigrateDatabaseToLatestVersion

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>());
        }

In migrations Up method there are also sql queries with static data (I don't use a Seed method in Configuration class). 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](DbExpressionVisitor1 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](DbExpressionVisitor1 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.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.b__2()
w System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
w System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass3.b__1()
w System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func1 operation)
w System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)
w System.Data.Entity.Core.Objects.ObjectQuery1.<System.Collections.Generic.IEnumerable.GetEnumerator>b__0()
w System.Lazy1.CreateValue()
w System.Lazy1.LazyInitValue()
w System.Lazy1.get_Value()
w System.Data.Entity.Internal.LazyEnumerator1.MoveNext()
w System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source)
w System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.b__2[TResult](IEnumerable1 sequence)
w System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 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()

No Entity Framework provider found for the ADO.NET provider with invariant name 'Effort.Provider'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.

Presently, I am attempting to run a unit test using EFFORT, but I'm getting the following error. This seems odd, because I clearly have Effort.Provider.EffortProviderConfiguration.RegisterProvider(); in my test setup. Please note that I am using the Effort and NMemory C# projects instead of installing with NuGet because I am trying to troubleshoot a MultipleUniqueKeyFoundException exception. Does anyone have any suggestions?

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=No Entity Framework provider found for the ADO.NET provider with invariant name 'Effort.Provider'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.Infrastructure.DependencyResolution.DefaultProviderServicesResolver.GetService(Type type, Object key)
       at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
       at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
       at System.Data.Entity.Infrastructure.DependencyResolution.RootDependencyResolver.GetService(Type type, Object key)
       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
       at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
       at System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver`2.GetService(Type type, Object key)
       at System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetService[T](IDbDependencyResolver resolver, Object key)
       at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.<>c__DisplayClass1.<ResolveManifestToken>b__0(Tuple`3 k)
       at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
       at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
       at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
       at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
       at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
       at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
       at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
       at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
       at System.Data.Entity.Migrations.DbSetMigrationsExtensions.GetKeyProperties[TEntity](Type entityType, InternalSet`1 internalSet)
       at System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](IDbSet`1 set, TEntity[] entities)
       at Cpr.Apps.Sam.Test.Model.Integration.Helpers.EffortEamEntitiesTestData.AddTestData(IEamEntities context) in C:\src\trunk\Cpr.Apps.Sam.Test.Model.Integration\Helpers\EffortEamEntitiesTestData.cs:line 37
       at Cpr.Apps.Sam.Test.Model.Integration.Helpers.IntegrationTest.IntegrationTestSetup() in C:\src\trunk\Cpr.Apps.Sam.Test.Model.Integration\Helpers\IntegrationTest.cs:line 51
  InnerException: 

DatabaseGeneratedOption.None Ignored

I have the following class:

public Message
{
      [Key]
      public long GId;

      [DatabaseGenerated(DatabaseGeneratedOption.None)]  
      public int Id;
}

I insert multiple messages with multiple Id's. After SaveChanges() all values in the fields Id are resetted to 1. GId is properly set and incremented after each insert, but Id is ALWAYS 1. It is impossible to change the value in this case!

Any known workaround for this?

Testing code using Microsoft.AspNet.Identity.EntityFramework.* things

Hey, hope you'd be able to help me out here as I cannot figure out a solution.

Setup in tests:

_kernel.Rebind<DbConnection>().ToConstant(Effort.DbConnectionFactory.CreateTransient());

Context:

public class MyDbContext : IdentityDbContext<MyApplicationUser>
{
    public MyDbContext()
        : base("DefaultConnection", false)
    {
        // This is version I want to start injecting dbconnection into, like below
        // <add name="DefaultConnection" connectionString="data source=localhost;initial catalog=MyDbTable;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
    }

    public MyDbContext(DbConnection connection)
        : base(connection.ConnectionString, false)
    {
        Console.WriteLine(connection.ConnectionString); // instanceid=0c8baee5-5790-4b37-9772-49fe7da75f43
    }
}

Result:

System.ArgumentException: Keyword not supported: 'instanceid'.

Thanks for your time and "Effort" :)

Multi-core or Multi thread doesn't works fine randomly

Hi .
We find that the following exception occurs occasionally at multiple cores or multiple threads

System.Data.Entity.Infrastructure.CommitFailedException : An error was reported while committing a database transaction but it could not be determined whether the transaction succeeded or failed on the database server. See the inner exception and http://go.microsoft.com/fwlink/?LinkId=313468 for more information.
        ---- System.Transactions.TransactionAbortedException : ๅทฒไธญๆญขไบ‹ๅŠกใ€‚
        -------- System.TimeoutException : ไบ‹ๅŠก่ถ…ๆ—ถ
        Stack Trace:
             ๅœจ System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
             ๅœจ System.Data.Entity.Infrastructure.Interception.DbTransactionDispatcher.Commit(DbTransaction transaction, DbInterceptionContext interceptionContext)
             ๅœจ System.Data.Entity.Core.EntityClient.EntityTransaction.Commit()
             ๅœจ System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
             ๅœจ System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
             ๅœจ System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
             ๅœจ System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
             ๅœจ System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
             ๅœจ System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
             ๅœจ System.Data.Entity.Internal.InternalContext.SaveChanges()
             ๅœจ System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
             ๅœจ Abp.EntityFramework.AbpDbContext.SaveChanges()

          ----- Inner Stack Trace -----
             ๅœจ System.Transactions.TransactionStateAborted.BeginCommit(InternalTransaction tx, Boolean asyncCommit, AsyncCallback asyncCallback, Object asyncState)
             ๅœจ System.Transactions.CommittableTransaction.Commit()
             ๅœจ Effort.Provider.EffortTransaction.Commit()
             ๅœจ System.Data.Entity.Infrastructure.Interception.DbTransactionDispatcher.<Commit>b__c(DbTransaction t, DbTransactionInterceptionContext c)
             ๅœจ System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
          ----- Inner Stack Trace -----

I am use xunit test framework in 4 Multi-core .
Can you have an idea ?
Thanks

NUnit, first run after a build, slow

Cross-posting this issue from CodePlex as I'm experiencing the exact same issue:

Hey,
I started a new project in which I want to make some integration testing using Effort. Since it's the beginning of the project, I'm often rebuilding the test project after small changes. When I first run the tests, it takes me around 10 seconds to run a couple of tests. After that it's under a second.
Any recommendations on this issue?

Extreme performance drop after switching to code first

I have about 1000 Tests running with Effort.
I use CreateTransient so that each Test gets it's own fresh Database.
I recently switched from Database First to Code First and noticed a significant performance drop.
The Tests used to run in about 40 Minutes and are now taking about 2.4 hours to complete.
This is an increase of about 6 seconds per Test.

I did a lot of profiling and the problem seems to come from code first creating a new database for every test.
The drop comes from System.Data.Entity.Internal.InternalContext.InitializeDatabase() which is called whenever an operation is executed on a new Connection that I created using CreateTransient(...).

I tried turning of DB Initialization with Database.SetInitializer(null), but then I get an error from Effort that says I need to initialize the Database when using code first.

I also tried using CreatePersistent and using a Transaction on the connection which gets rolled back in TestInitialize, but the Rollback was not executed to the Data from Test1 ended up in Test2.

Is there anything else I can do to return the performance to a normal Level?
I would be happy to create a Pull Request if there is anything that I can change in the Effort code too.

NuGet complains about packages.config in Visual Studio

I'm unable to build the solution because NuGet complains about duplicate EntityFramework entries in packages.config for the Effort.Test and Effort.Test.Data projects. I commented out the version I didn't want and it builds but I'm not certain this will break something else if I submit a PR for it. Tested in VS2015.

Support for custom code first conventions

I'm getting the impression Effort doesn't support custom code first conventions.
I create a basic convention as following:

    public class DateTime2Convention : Convention
    {
        public DateTime2Convention()
        {
            this.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
        }
    }

and declaring it in OnModelCreating:

modelBuilder.Conventions.Add(new DateTime2Convention()); 

Works fine with a real DB, but crashes with Effort:

Test Name:  TestXXX
Test FullName:  Domain.Data.Test.Model.EfXXXUnitTest.TestNumeroReference
Test Source:    EfXXXUnitTest.cs : line 57
Test Outcome:   Failed
Test Duration:  0:00:00.0342313

Result Message: 
Test method Domain.Data.Test.Model.EfXXXUnitTest.TestNumeroReference threw exception: 
System.InvalidOperationException: Sequence contains no matching element
Result StackTrace:  
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
   at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name)
   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty column, EntityType table, DbProviderManifest providerManifest)
   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty column, EntityType table, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)
   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.<>c__DisplayClass4.<Configure>b__3(Tuple`2 pm)
   at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(IEnumerable`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)
   at System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride)
   at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
   at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
   at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
   at Domain.Data.Model.EfXXXRepository.ListForNumeroReference(String NumeroReference) in Domain.Data\Model\EfXXXRepository.cs:line 22
   at Domain.Data.Test.Model.EfXXXUnitTest.TestForNumeroReference() in Domain.Data.Test\Model\EfXXXUnitTest.cs:line 58

Reversed properties not working

In case you have table B with on column IdTableA referencing table A'Id, when your query is such as :
context.TableA.Select(a=>a.TableBCollection.Where(b=>b....))
The where is not working, and I get every element of table b without my discrimator being taken care of.
For example I got :
b.Service.Subscriptions.Any(s => s.Attendee.AccountId == accountId));
b is a budget, with a Service Id in the database, but Subscriptions has a Service Id so this is a reverse property, Service is not holding onto subscription, but subscriptions is targeting a service.
The Any part is not taken into account. :(

Interpreting 0 and 1 as booleans

Hi!

I've exported some tables from our MySQL db to csv files. However, Effort complains when loading the data, because boolean columns are zeros and ones (as in a db table). It seems to want the text "true" or "false". Is there anyway to configure it to accept data the way it looks when exporting from a database?

MigrationsException with IdentityModel 2.2.0: No MigrationSqlGenerator found for provider 'Effort.Provider'

According to latest news the IdentityModel 2.2 finally added a ctor overload without the CompiledModel parameter. However, running all the latest nugets (EF 6.1.2 + Effort.EF6 1.1.4 + identity model 2.2.0) I'm getting the below exception.

I tried adding SetSqlGenerator("Effort.Provider", new SqlServerMigrationSqlGenerator()); to Configuration.cs ctor, but that left me with some incompatible provider exception.

I always seem to struggle trying to use Effort with the ApplicationDbContext that comes out of the box with ASP.net. Am I doing something wrong or is it simply not supported? Other contexts inheriting from DbContext work fine, but not when inheriting from IdentityDbContext.

System.Data.Entity.Migrations.Infrastructure.MigrationsException : No MigrationSqlGenerator found for provider 'Effort.Provider'. Use the SetSqlGenerator method in the target migrations configuration class to register additional SQL generators.
   at System.Data.Entity.Migrations.DbMigrationsConfiguration.GetSqlGenerator(Stringย providerInvariantName)
   at System.Data.Entity.Migrations.DbMigrator.GenerateStatements(IList`1ย operations,ย Stringย migrationId)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(Stringย migrationId,ย VersionedModelย targetModel,ย IEnumerable`1ย operations,ย IEnumerable`1ย systemOperations,ย Booleanย downgrading,ย Booleanย auto)
   at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigrationย migration,ย DbMigrationย lastMigration)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1ย pendingMigrations,ย Stringย targetMigrationId,ย Stringย lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Actionย mustSucceedToKeepDatabase)
   at System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContextย context)
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Actionย action)
   at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
   at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInputย input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1ย action)
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Typeย entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Actionย action,ย EntityStateย newState,ย Objectย entity,ย Stringย methodName)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Objectย entity)
   at System.Data.Entity.DbSet`1.Add(TEntityย entity)

NMemory.Exceptions.MultipleUniqueKeyFoundException : Error code: GenericError

Presently, I'm getting this exception when I run a unit test. I'm guessing it is a problem with my class metadata key values. What seems strange to me is that the two objects I'm inserting to have the same asset ID, but they are the same because it is a foreign-key relationship. Does anyone have any suggestions on how to narrow down where the problem is? TIA.

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 : Exception has been thrown by the target of an invocation.
  ----> NMemory.Exceptions.MultipleUniqueKeyFoundException : Error code: GenericError
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Cpr.Apps.Sam.Model.Base.AdoNetRepository`1.<Save>d__48.MoveNext() in C:\src\trunk\Cpr.Apps.Sam.Model\Base\AdoNetRepository.cs:line 598
--- 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.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Cpr.Apps.Sam.Test.Model.Integration.Integration.Repositories.InspectionRepositoryTests.<WillCallCompleteInspectionWithInspectionRepository>d__7.MoveNext() in C:\src\trunk\Cpr.Apps.Sam.Test.Model.Integration\Integration\Repositories\InspectionRepositoryTests.cs:line 74
--- End of stack trace from previous location where exception was thrown ---
   at NUnit.Framework.Internal.ExceptionHelper.Rethrow(Exception exception)
   at NUnit.Framework.Internal.AsyncInvocationRegion.AsyncTaskInvocationRegion.WaitForPendingOperationsToComplete(Object invocationResult)
   at NUnit.Framework.Internal.Commands.TestMethodCommand.RunAsyncTestMethod(TestExecutionContext context)
--UpdateException
   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()
--TargetInvocationException
   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 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.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   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()
--MultipleUniqueKeyFoundException
   at NMemory.DataStructures.UniqueHashtable`2.Insert(TKey key, TEntity entity)
   at NMemory.Execution.CommandExecutor.ExecuteInsert[T](T entity, IExecutionContext context)
   at NMemory.Tables.DefaultTable`2.InsertCore(TEntity entity, Transaction transaction)
   at Effort.Internal.DbManagement.Engine.ExtendedTable`2.InsertCore(TEntity entity, Transaction transaction)
   at NMemory.Tables.Table`2.Insert(TEntity entity, Transaction transaction)

---> 2016-09-26 16:18:29 -06:00 [INFO] [GENERAL] Saving changes to the database... / AdoNetRepository.cs:591 (2.26.0.3604) [Save()]
---> 2016-09-26 16:18:29 -06:00 [INFO] [GENERAL] Save successfull. / AdoNetRepository.cs:599 (2.26.0.3604) [Save()]
---> 2016-09-26 16:18:30 -06:00 [INFO] [GENERAL] Saving changes to the database... / AdoNetRepository.cs:591 (2.26.0.3604) [Save()]

Stored procedure

Hey tamasflamich,

I have a stored procedure which will return id generated from db. I was wondering if there is any way to mock this stored procedure call using Effort. I have in memory Id generator but I don't see a documentation how to inject this whenever store procedure is called.

My apologies if my question doesn't make sense.

Thanks

Readme needs a quick, get started, sample.

I would/will write one once I get more familiarized with the tool. But it does seem there is a barrier to entry here as I see no other way than examining the code to learn how to leverage this tool.

Multi thread xunit tests randomly fails

Hi,

Some of our unit tests randomly fails because of the following exception:

System.Data.Entity.Infrastructure.CommitFailedException : An error was reported while committing a database transaction but it could not be determined whether the transaction succeeded or failed on the database server. See the inner exception and http://go.microsoft.com/fwlink/?LinkId=313468 for more information.
---- System.Transactions.TransactionAbortedException : The transaction has aborted.
-------- System.TimeoutException : Transaction Timeout

When we run it single threaded, it works fine. Also, most of times all unit tests works normally, but sometimes it throws that exception.

Do you have an idea?
Thanks.

System.InvalidOperationException: Sequence contains more than one matching element

Hi,

I'm getting this exception when I use IQueryable:

System.Data.DataException: An exception occurred while initializing the database. See the InnerException for details. ---> 
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: Exception has been thrown by the target of an invocation. ---> 
NMemory.Exceptions.NMemoryException: Error code: GenericError ---> 
System.InvalidOperationException: Sequence contains more than one matching element

    at System.Linq.Enumerable.SingleOrDefault(IEnumerable`1ย source,ย Func`2ย predicate)
   at NMemory.Tables.TableCollection.FindTable(Typeย entityType)
   at NMemory.Utilities.TableCollectionExtensions.FindTable(TableCollectionย tableCollection)
   at NMemory.Execution.CommandExecutor.ExecuteInsert(Tย entity,ย IExecutionContextย context)
   at NMemory.Tables.DefaultTable`2.InsertCore(TEntityย entity,ย Transactionย transaction)
   at Effort.Internal.DbManagement.Engine.ExtendedTable`2.InsertCore(TEntityย entity,ย Transactionย transaction)
   at NMemory.Tables.Table`2.Insert(TEntityย entity,ย Transactionย transaction)
 --- End of inner exception stack trace ---
    at NMemory.Tables.Table`2.Insert(TEntityย entity,ย Transactionย transaction)
   at Effort.Internal.Common.DatabaseReflectionHelper.WrapperMethods.InsertEntity(ITable`1ย table,ย TEntityย entity,ย Transactionย transaction)
 --- End of inner exception stack trace ---
    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.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommandย t,ย DbCommandInterceptionContext`1ย c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTargetย target,ย Func`3ย operation,ย TInterceptionContextย interceptionContext,ย Action`3ย executing,ย Action`3ย executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommandย command,ย DbCommandInterceptionContextย interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2ย identifierValues,ย List`1ย generatedValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
 --- End of inner exception stack trace ---
    at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslatorย ut)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(Tย noChangesResult,ย Func`2ย updateFunction)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1ย func,ย IDbExecutionStrategyย executionStrategy,ย Booleanย startLocalTransaction,ย Booleanย releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptionsย options,ย IDbExecutionStrategyย executionStrategy,ย Booleanย startLocalTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
   at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute(Func`1ย operation)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptionsย options,ย Booleanย executeInExistingTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptionsย options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
 --- End of inner exception stack trace ---
    at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at System.Data.Entity.Migrations.History.HistoryRepository.BootstrapUsingEFProviderDdl(VersionedModelย versionedModel)
   at System.Data.Entity.Internal.InternalContext.<SaveMetadataToDatabase>b__7()
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Actionย action)
   at System.Data.Entity.Internal.InternalContext.SaveMetadataToDatabase()
   at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContextย internalContext,ย Func`3ย createMigrator,ย ObjectContextย objectContext)
   at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContextย objectContext,ย DatabaseExistenceStateย existenceState)
   at System.Data.Entity.Database.Create(DatabaseExistenceStateย existenceState)
   at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContextย context)
   at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Actionย action)
 --- End of inner exception stack trace ---
    at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Actionย action)
   at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
   at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContextย c)
   at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInputย input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1ย action)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Typeย entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Count(IQueryable`1ย source)

   at Model.MyProj... my test method call stack here

to reproduce:

var query = db.MyEntities.Count(); // will throw the exception above FOR SOME DBCONTEXTS ONLY!!!

Otherwise all other tests work just fine with Effort. Created a more detailed question here:
http://stackoverflow.com/questions/36053318/effort-throws-invalidoperationexception-sequence-contains-more-than-one-matchin

I checked the DbContext that causes the problem and could not find anything special about it. Any ideas?

Thanks

Can Effort be used with ADO.NET directly? (e.g. for Dapper)

I understand that Effort is mainly targeted towards Entity Framework-applications, but an in-memory database would be nice to have in other applications as well.

I am working on an application that uses Dapper with a ADO.NET IDbConnection and would like to use Effort to run database tests. Is this possible / intended?

EffortProviderServices doesn't inherit from 'System.Data.Entity.Core.Common.DbProviderServices'

I get a System.InvalidOperationException on the second line:

    var connection = DbConnectionFactory.CreatePersistent(Guid.NewGuid().ToString());
    ApplicationDbContext db = new ApplicationDbContext(connection);

It happens inside the Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext<ApplicationUser>.ctor I'm deriving from:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbConnection connection) : base(connection, false)
        {
        }
    }

Here's the complete exception

System.InvalidOperationException occurred
  HResult=-2146233079
  Message=The 'Instance' member of the Entity Framework provider type 'Effort.Provider.EffortProviderServices, Effort, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6a46696d54971e6d' did not return an object that inherits from 'System.Data.Entity.Core.Common.DbProviderServices'. Entity Framework providers must inherit from this class and the 'Instance' member must return the singleton instance of the provider. This may be because the provider does not support Entity Framework 6 or later; see http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(Type providerType)
       at System.Data.Entity.Internal.AppConfig.<.ctor>b__2(ProviderElement e)
       at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at System.Lazy`1.CreateValue()
       at System.Lazy`1.LazyInitValue()
       at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.RegisterDbProviderServices()
       at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServiceFactory(Type type, String name)
       at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
       at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetService(Type type, Object key)
       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
       at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
       at System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver`2.GetService(Type type, Object key)
       at System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetService[T](IDbDependencyResolver resolver)
       at System.Data.Entity.DbContext.InitializeLazyInternalContext(IInternalConnection internalConnection, DbCompiledModel model)
       at Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext`1..ctor(DbConnection existingConnection, Boolean contextOwnsConnection)
       at MyProject.ApplicationDbContext..ctor(DbConnection connection) in ..\MyProject\ApplicationDbContext.cs:Zeile 16.
  InnerException: 

I tried to fix the App.config but it didn't help

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
      </configSections>
      <entityFramework>
        <providers>
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
      </entityFramework>
    </configuration>

Exception when working with Automapper's ProjectTo (multiple collection mappings)

Exception:

Index was outside the bounds of the array.

Simplified code to replicate:

var measures = DataContext.People.ProjectTo<PersonModel>().ToArray();

public class PersonEntity
{
       [Key]       
        public int Id { get; set; } 
        public string Name { get; set; } 
        public virtual ICollection<AccomplishmentEntity> Accomplishments{ get; set; } 
        public virtual ICollection<GoalEntity> Goals{ get; set; } 
}

public class PersonModel
{
        public int Id { get; set; } 
        public string Name { get; set; } 
        public IEnumerable<Accomplishment> Accomplishments{ get; set; } 
        public IEnumerable<Goal> Goals{ get; set; } 
}

public class PersonMapperProfile: Profile  
{  
        public PersonMapperProfile()  
        {  
                CreateMap<PersonEntity, PersonModel>()  
                .ForMember(dest => dest.Name, opt => opt.MapFrom(x => x.Name))  
                .ForMember(dest => dest.Accomplishments, opt => opt.MapFrom(x => x.Accomplishments))  
                .ForMember(dest => dest.Goals, opt => opt.MapFrom(x => x.Goals));  
        }  
}

The problem seems to lie in the fact the we're trying to project to multiple collections and Effort can't handle that. If we map any one of the collections while ignoring the other, everything works well. The simplest workaround for now seems to be to use AutoMapper.Mapper.Map instead of ProjectTo but I'm always hesitant to change production code to fit the limitations of tests. Entity Framework itself seems to know how to handle this pretty well, so this just fails in unit tests with Effort.

Looking for suggestions and feedback :)

StackTrace:

System.Data.Entity.Core.EntityCommandExecutionException : An error occurred while executing the command definition. See the inner exception for details.
  ----> System.IndexOutOfRangeException : Index was outside the bounds of the array.
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
   at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Crestone.ProjectCoulomb.Web.Handlers.Pqrs.GetMeasuresRequestHandler.Execute(Int32 caseId) in C:\Projects\<ProjectPath>\Handlers\Pqrs\GetMeasuresRequestHandler.cs:line 24
   at <ProjectName>.QaMeasures.QaMeasures.RegisterAndInsertIntoDb() in C:\Projects\<ProjectPath>\QaMeasures\QaMeasures.cs:line 50
--IndexOutOfRangeException
   at NMemory.Common.LinqJoinKeyHelper.CreateKeySelectors(Type outerType, Type innerType, IExpressionBuilder[] outerKeyCreator, IExpressionBuilder[] innerKeyCreator, LambdaExpression& outerKey, LambdaExpression& innerKey)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.Optimization.Rewriters.InnerJoinLogicalRewriter.VisitMethodCall(MethodCallExpression node)
   at NMemory.Execution.QueryCompilerBase.TransformExpression(Expression expression, ITransformationContext context, TransformationStepRecorder recorder)
   at NMemory.Execution.QueryCompilerBase.Compile[T](Expression expression)
   at NMemory.Linq.TableQuery`1.GetEnumerator(IDictionary`2 parameters, Transaction transaction)
   at NMemory.Linq.TableQueryWrapper`1.System.Collections.IEnumerable.GetEnumerator()
   at Effort.Provider.EffortDataReader..ctor(IEnumerable result, Int32 recordsAffected, FieldDescription[] fields, DbContainer container)
   at Effort.Internal.CommandActions.QueryCommandAction.ExecuteDataReader(ActionContext context)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)

AccessViolationException - Attempted to read or write protected memory

Hello,
So I am using the Effort.EF6 (1.1.4) and NMemory(1.1.2) framework for my Unit Tests - now I have only recently returned to using Effort after deciding it was probably the best route for my situation. I have been using the framework for the past month without an issue, until yesterday morning I came across an:

AccessViolationException was unhandled by user code

An exception of type 'System.AccessViolationException' occurred in NMemory.dll but was not handled in user code

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

The particular case I refer to seems to happen when trying to perform a LINQ Where(x => x.) on one of the properties of my DbContext. I will check my other unit tests to see if it is just querying that it occurs on.

Now I have seen this issue before (https://effort.codeplex.com/discussions/632411) however it was never my laptop.

Any ideas on what is causing this?? It is just strange that it reappeared yesterday.

Multiple DbContexts not synchronizing data

Entity Framework: 6.1.3
Database-first approach
Repro:

EntityConnection connection = Effort.EntityConnectionFactory.CreateTransient(connectionString);
var dbContext = new MyDbContext(connection);
dbContext.Users.Add(new User() { UserName= "John" });
dbContext.SaveChanges();

var dbContext2 = new MyDbContext(connection);
var user = dbContext2.Users.FirstOrDefault();

user.UserName= "Mike";
dbContext2.SaveChanges();

// This fails
Assert.AreEqual(dbContext.Users.FirstOrDefault().UserName,
                                       dbContext2.Users.FirstOrDefault().UserName);

The workaround is that I have to re-initialize "dbContext" before the Assert statement:
dbContext = new MyDbContext(connection);

Is this by design? I've even tried the persistent connection but it's the same behavior.

EffortException while running unit tests

Hi,
I'm using Effort to mock connection to my database connection. It works fine when I run single test, but when I run multiple tests I receive the following exception:

Result StackTrace:  
at Effort.DbConnectionFactory.CreateTransient()
   at Tests.MyTest..ctor() 
----- Inner Stack Trace -----
   at Effort.Provider.EffortProviderConfiguration.RegisterDbConfigurationEventHandler()
   at Effort.Provider.EffortProviderConfiguration.RegisterProvider()
   at Effort.DbConnectionFactory..cctor()
----- Inner Stack Trace -----
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.AddLoadedHandler(EventHandler`1 handler)
   at System.Data.Entity.DbConfiguration.add_Loaded(EventHandler`1 value)
   at Effort.Provider.EffortProviderConfiguration.RegisterDbConfigurationEventHandler()
Result Message: 
System.TypeInitializationException : The type initializer for 'Effort.DbConnectionFactory' threw an exception.
---- Effort.Exceptions.EffortException : The Effort library failed to register its provider automatically, so manual registration is required.

a) Call the Effort.Provider.EffortProviderConfiguration.RegisterProvider() method at entry point of the application

or

b) Add the following configuration to the App.config file:
   <system.data>
      <DbProviderFactories>
         <add name="Effort.Provider"
              invariant="Effort.Provider"
              description="Effort.Provider"
              type="Effort.Provider.EffortProviderFactory, Effort" />
      </DbProviderFactories>
   </system.data>


   <entityFramework>
      <providers>
         <provider invariantName="Effort.Provider"
                   type="Effort.Provider.EffortProviderServices, Effort" />
      </providers>
   </entityFramework>
-------- System.InvalidOperationException : The Entity Framework was already using a DbConfiguration instance before an attempt was made to add an 'Loaded' event handler. 'Loaded' event handlers can only be added as part of application start up before the Entity Framework is used. See http://go.microsoft.com/fwlink/?LinkId=260883 for more information.

I have added mentioned configuration to app.config but it doesn't work. I can't add RegisterProvides() because I'm using xunit.net and it doesn't provide me any entry point.

Below is my code from MyTest constructor:

var connection = DbConnectionFactory.CreateTransient();
var context = new Mock<PaymentTransactionsDbContext>(connection, true);

Oracle Entity Framework Generated Context Exception:Schema specified is not valid. Errors: (0,0) : error 2019: Member Mapping specified is not valid. The type 'Edm.Boolean[Nullable=True,DefaultValue=]' ...

Hi, awesome Effort and code!
I'm trying to use it for Oracle, I've fixed Export CSV Tool, now I'm trying to run simple example:

var dl = new CsvDataLoader("...");
var connection = Effort.EntityConnectionFactory.CreateTransient("name=EapEntities", dl);
var db = new EapEntities(connection);
db.CM_HUMAN.Take(100).Dump();

and getting this errors:
MappingException: Schema specified is not valid. Errors:
(0,0) : error 2019: Member Mapping specified is not valid. The type 'Edm.Boolean[Nullable=True,DefaultValue=]' of member 'DEFAULT_FLAG' in type 'Model.CE_CATALOG_ENTRY_NG' is not compatible with 'Effort.decimal[Nullable=True,DefaultValue=,Precision=1,Scale=0]' of member 'DEFAULT_FLAG' in type 'Model.Store.CE_CATALOG_ENTRY_NG'.
(0,0) : error 2019: Member Mapping specified is not valid. The type 'Edm.Boolean[Nullable=True,DefaultValue=]' of member 'CITY_LOOKUP_BROKEN' in type 'Model.CM_ADDRESS' is not compatible with 'Effort.decimal[Nullable=True,DefaultValue=,Precision=1,Scale=0]' of member 'CITY_LOOKUP_BROKEN' in type 'Model.Store.CM_ADDRESS'.
(0,0) : error 2019: Member Mapping specified is not valid.

I've attached debugger and can see that error happening at:

at Effort.Internal.Common.MetadataWorkspaceHelper.CreateMetadataWorkspace(List1 csdl, List1 ssdl, List`1 msl)

at this line in \effort-master\Main\Source\Effort\Internal\Common\MetadataWorkspaceHelper.cs

        StorageMappingItemCollection smic = new StorageMappingItemCollection(eic, sic, msl.Select(c => c.CreateReader()));

at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.Init(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable1 xmlReaders, IList1 filePaths, Boolean throwOnError)
at System.Data.Entity.Core.Mapping.StorageMappingItemCollection..ctor(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable1 xmlReaders) at Effort.Internal.Common.MetadataWorkspaceHelper.CreateMetadataWorkspace(List1 csdl, List1 ssdl, List1 msl)
at Effort.Internal.Common.MetadataWorkspaceHelper.Rewrite(String metadata, String providerInvariantName, String providerManifestToken)
at Effort.EntityConnectionFactory.b__1(String metadata)
at Effort.Internal.Caching.MetadataWorkspaceStore.<>c__DisplayClass1.b__0()
at System.Lazy1.CreateValue() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Lazy1.get_Value()
at Effort.Internal.Caching.ConcurrentCache2.Get(TKey key, Func1 factory)
at Effort.Internal.Caching.MetadataWorkspaceStore.GetMetadataWorkspace(String metadata, Func`2 workspaceFactoryMethod)
at Effort.EntityConnectionFactory.GetEffortCompatibleMetadataWorkspace(String& entityConnectionString)
at Effort.EntityConnectionFactory.CreateTransient(String entityConnectionString, IDataLoader dataLoader)
at UserQuery
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

Any ideas appreciated ๐Ÿ‘

AmbiguousMatchException when enumerating DbSet.

Effort throws AmbiguousMatchException when calling DbSet.ToList().

We've discovered the cause of this behavior:
There are two entities which are mapped to tables with similar names: WUBS.InstructionStatus and APN.InstructionStatus. The only difference is namespace. Whenever we change the name of either of the table everything works fine.

Add support of LongCount aggregate function

I am using Effort.EF6 library version 1.1.4 from nuget.org.

I try to use LongCount function on IQueryable provided by Effort library, I get an error:

"BigCount is not a not supported DbFunctionAggregate"

Hovever, on real Entity Framework connection LongCount fully supported.
Please add support of LongCount function, this is requried by unit tests.

P.S. I suppose corrent error message is "BigCount is not a supported DbFunctionAggregate", without second "not".

Multiple persistent connections

Allow for the creation of persistent connections with different identifiers when using the EntityConnectionFactory with a database first connection.

CsvDataLoader database is not initialized

Hello,
I want to initialize my database with data using csvdataloader. So, I'm trying to do the following ( as in guide)

        [Test]
        public void IsUserModelPropertiesMappedCorrectly()
        { 
            var dataLoader = new CsvDataLoader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TestDataFolderName));
            var inMemoryDbConnection = Effort.DbConnectionFactory.CreateTransient(dataLoader);

            using (var ctx = new AppDbContext(inMemoryDbConnection))
            {
                
                var firstUser = ctx.Set<User>().First(); // here I'm getting the exception  
                .................................       //  Database has not been initialized.If using CodeFirst  try to add the following line:  context.Database.CreateIfNotExists()          

            }
        }

My AppDbContext looks like this

public class AppDbContext : DbContext
    {
        public AppDbContext(DbConnection connection, IDatabaseInitializer<AppDbContext> dbInitializer = null)
            : base(connection, true)
        {
            Database.SetInitializer(dbInitializer);         
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Configurations.Add(new UserTypeConfiguration());
            modelBuilder.Configurations.Add(new RoleTypeConfiguration());
            modelBuilder.Configurations.Add(new PostTypeConfiguration());
            modelBuilder.Configurations.Add(new CommentTypeConfiguration());
            modelBuilder.Configurations.Add(new PermissionTypeConfiguration());
            modelBuilder.Configurations.Add(new RecordTypeConfiguration());
        }
    }

And even if I execute the context.Database.CreateIfNotExists(), the database is created but is not initialized with my csv data?
So, could you explain why I'm getting this result?

Provide InstanceId in EntityConnectionFactory

We are using the EntityConnectionFactory for our database connction. For our UnitTests the database should be persistent, but only persistent for each test / testfixture.

I have found a create method for an special instanceId. But it is only implemented in the DbConnectionFactory. Within the EntityConnectionFactory the instanceId will be setted.

if (persistent)
{
    ecsb.InstanceId = entityConnectionString;
}
else
{
     ecsb.InstanceId = Guid.NewGuid().ToString();
}

The idea is to set the instanceId for each test. Can you provide a overload to set the instanceId within the EntityConnectionFactory additionally to the Guid.NewGuid().ToString()?

DatabaseGeneratedOption.Computed always causes null

I have a column like the following:

    [Column, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime? LastModified { get; set; }

and a SQL trigger that sets it as expected. Entity framework expects the database to set this property and reads it back after each insert and update. Effort always reports this as null. That is:

    var entity = new MyEntity { LastModified = DateTime.Now };
    dbContext.MyEntities.Add(entity);
    dbContext.SaveChanges();
    Assert.NotNull(entity.LastModified);

fails where dbContext is a DbContext created from a transcient Effort DbConnection.

I would like some mechanism to get around this. Perhaps an EntityWithComputedColumnInserting event and an EntityWithComputedColumnUpdating event for allowing users to handle the computing of computed columns. Say using an EventArgs similar to the following:

    public class ComputedColumnEventArgs : EventArgs
    {
        public Type EntityType { get; }
        public string ComputedColumnName { get; }
        public object ComputedValue { get; set; }
    }

I could then make an event handler like the following in my test class:

    private void ComputeLastModified(object sender, ComputedColumnEventArgs e)
    {
        if (e.EntityType = typeof(MyEntity) 
            && e.ComputedColumnName == nameof(MyEntity.LastModified))
        {
            e.ComputedValue = _now;
        }
    }

Initializing two dbContext data failed

when I initialized two dbcontext data ,it throw exception at the method of dbcontext's SaveChanges().
like that:

{"Table 'XXXXXX' was not found. The database was probably not initialized.\r\n\r\nIf using CodeFirst try to add the following line:\r\ncontext.Database.CreateIfNotExists()"}

System.NotSupportedException : Specified method is not supported. at Effort.Provider.EffortCommand.ExecuteNonQuery()

Presently, in my unit test, I have:

        [Test]
        public void WillRetrieveTrackGradeIfItExists()
        {
            //Arrange
            InsertAssetCharacteristicAndValue(asset, AssetCharacteristicClassName.BRIDGE, AssetCharacteristicName.TRACK_GRADE, 11.23M);
            using (var cmd = ConnectionProviderBase.Connection.CreateCommand())
            {
                cmd.CommandText = "SELECT * FROM class";
                using (var reader = cmd.ExecuteReader())
                {
                    reader.HasRows.Should().BeTrue();
                }
            }

            //Act
            var results = Repository.FindMultipleByAsset(asset, AssetCharacteristicClassName.BRIDGE, AssetCharacteristicName.TRACK_GRADE).ToArray();

            //Assert
            results.Should().HaveCount(1);
            results[0].AssetCharacteristicName.Should().Be(AssetCharacteristicName.TRACK_GRADE.ToStorageValue<string>());
            results[0].NumericValue.Should().Be(11.23M);
        }

This results in the following function being called:

        private void InsertClassDefinition(string classId, string className)
        {
            using (var cmd = ConnectionProviderBase.Connection.CreateCommand())
            {
                var sql = @"INSERT INTO class ([CLASS_TYPE],[CLASS_NUM_INT],[CLASSNUM],[VALID_DATE_FROM],[VALID_DATE_TO]) VALUES('002',?,?,'1999-12-14','9999-12-31')";
                cmd.CommandText = sql;
                cmd.CommandType = CommandType.Text;
                CreateParameter(cmd, "@CLASS_NUM_INT", DbType.String, classId);
                CreateParameter(cmd, "@CLASS_NUM", DbType.String, className);

                cmd.ExecuteNonQuery();
            }
        }

        private void CreateParameter(DbCommand cmd, string parameterName, DbType dbType, object value)
        {
            IDbDataParameter parameter;

#if EFFORT 
            parameter = new EffortParameter();
#else 
            parameter = new SAParameter();
#endif
            parameter.ParameterName = parameterName;
            parameter.DbType = dbType;
            parameter.Value = value;
            cmd.Parameters.Add(parameter);
        }

When it reaches the cmd.ExecuteNonQuery(), then I get this exception:

System.NotSupportedException : Specified method is not supported.
at Effort.Provider.EffortCommand.ExecuteNonQuery()
at Test.Model.Integration.Integration.Repositories.BaseAssetCharacteristicRepositoryTest.InsertClassDefinition(String classId, String className) in c:\Projects\Test.Model.Integration\Integration\Repositories\BaseAssetCharacteristicRepositoryTest.cs:line 115
at Test.Model.Integration.Integration.Repositories.BaseAssetCharacteristicRepositoryTest.InsertAssetCharacteristicAndValue(InspectionAsset asset, AssetCharacteristicClassName assetType, AssetCharacteristicName characteristicName, Decimal value) in c:\Projects\Test.Model.Integration\Integration\Repositories\BaseAssetCharacteristicRepositoryTest.cs:line 151
at Test.Model.Integration.Integration.Repositories.AssetCharacteristicRepositoryFindMultipleByAssetTests.WillRetrieveTrackGradeIfItExists() in c:\Projects\Test.Model.Integration\Integration\Repositories\AssetCharacteristicRepositoryFindMultipleByAssetTests.cs:line 42

Does anyone have any suggestions? I have setup Effort basically according to this article: http://www.codeproject.com/Tips/1036630/Using-Effort-Entity-Framework-Unit-Testing-Tool

UPDATE:

One reason why it may not be working is because in the EF Database-First setup that I'm using, the EDMX file actually does not have a one-to-one relationship with classes to database tables for the class table. It is actually a query view in EDMX that pulls data from several tables to populate a single C# class called AssetCharacteristic. Ultimately there is no class table that the DB context points to, so that might explain why Effort cannot perform ExecuteNonQuery() against it.

Precision restriction not allowed on fields of type 'double'

I have an Entity model generated from a Sybase ASE database that contains the following table

 CREATE TABLE  z_script (
    script_id                       char(30)                         not null  ,
    release_id                      char(10)                         not null  ,
    description                     char(255)                        not null  ,
    script                          text                             not null  ,
    release_num                     char(7)                          not null  ,
    sequence_num                    float(16)                        not null  ,
    before_after                    char(1)                          not null  ,
    key_prefix                      varchar(10)                          null   
)

Which generates the following into the edmx file

SSDL content

<EntityType Name="z_script">
    <Key>
        <PropertyRef Name="script_id" />
    </Key>
    <Property Name="script_id" Type="char" MaxLength="30" Nullable="false" />
    <Property Name="release_id" Type="char" MaxLength="10" Nullable="false" />
    <Property Name="description" Type="char" MaxLength="255" Nullable="false" />
    <Property Name="script" Type="text" Nullable="false" />
    <Property Name="release_num" Type="char" MaxLength="7" Nullable="false" />
    <Property Name="sequence_num" Type="float" Precision="24" Nullable="false" />
    <Property Name="before_after" Type="char" MaxLength="1" Nullable="false" />
    <Property Name="key_prefix" Type="varchar" MaxLength="10" />
</EntityType>

CSDL content

<EntityType Name="z_script">
    <Key>
        <PropertyRef Name="script_id" />
    </Key>
    <Property Name="script_id" Type="String" Nullable="false" MaxLength="30" FixedLength="true" Unicode="false" />
    <Property Name="release_id" Type="String" Nullable="false" MaxLength="10" FixedLength="true" Unicode="false" />
    <Property Name="description" Type="String" Nullable="false" MaxLength="255" FixedLength="true" Unicode="false" />
    <Property Name="script" Type="String" Nullable="false" MaxLength="Max" FixedLength="false" Unicode="false" />
    <Property Name="release_num" Type="String" Nullable="false" MaxLength="7" FixedLength="true" Unicode="false" />
    <Property Name="before_after" Type="String" Nullable="false" MaxLength="1" FixedLength="true" Unicode="false" />
    <Property Name="key_prefix" Type="String" MaxLength="10" FixedLength="false" Unicode="false" />
    <Property Name="sequence_num" Type="Double" Nullable="false" />
</EntityType>

C-S Mapping

<EntitySetMapping Name="z_script">
    <EntityTypeMapping TypeName="DxP.Services.CopathPlus.Data.z_script">
        <MappingFragment StoreEntitySet="z_script">
            <ScalarProperty Name="sequence_num" ColumnName="sequence_num" />
            <ScalarProperty Name="key_prefix" ColumnName="key_prefix" />
            <ScalarProperty Name="before_after" ColumnName="before_after" />
            <ScalarProperty Name="release_num" ColumnName="release_num" />
            <ScalarProperty Name="script" ColumnName="script" />
            <ScalarProperty Name="description" ColumnName="description" />
            <ScalarProperty Name="release_id" ColumnName="release_id" />
            <ScalarProperty Name="script_id" ColumnName="script_id" />
        </MappingFragment>
    </EntityTypeMapping>
</EntitySetMapping>

When I load the model into Effort using Effort.EntityConnectionFactory.CreateTransient(), it throws the following exception

System.Data.MetadataException: Schema specified is not valid. Errors: 
(0,0) : error 0063: Precision facet isn't allowed for properties of type double.   
at System.Data.Metadata.Edm.StoreItemCollection.Loader.ThrowOnNonWarningErrors()   
at System.Data.Metadata.Edm.StoreItemCollection.Loader.LoadItems(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths)   
at System.Data.Metadata.Edm.StoreItemCollection.Loader..ctor(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, Boolean throwOnError)   
at System.Data.Metadata.Edm.StoreItemCollection.Init(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths, Boolean throwOnError, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerManifestToken, Memoizer`2& cachedCTypeFunction)   
at System.Data.Metadata.Edm.StoreItemCollection..ctor(IEnumerable`1 xmlReaders)   
at Effort.Internal.Common.MetadataWorkspaceHelper.CreateMetadataWorkspace(List`1 csdl, List`1 ssdl, List`1 msl)   
at Effort.Internal.Common.MetadataWorkspaceHelper.Rewrite(String metadata, String providerInvariantName, String providerManifestToken)   
at Effort.EntityConnectionFactory.<GetEffortCompatibleMetadataWorkspace>b__1(String metadata)   
at Effort.Internal.Caching.MetadataWorkspaceStore.<>c__DisplayClass1.<GetMetadataWorkspace>b__0()   
at System.Lazy`1.CreateValue()   at System.Lazy`1.LazyInitValue()   at System.Lazy`1.get_Value()   
at Effort.Internal.Caching.ConcurrentCache`2.Get(TKey key, Func`1 factory)   
at Effort.Internal.Caching.MetadataWorkspaceStore.GetMetadataWorkspace(String metadata, Func`2 workspaceFactoryMethod)   
at Effort.EntityConnectionFactory.GetEffortCompatibleMetadataWorkspace(String& entityConnectionString)   
at Effort.EntityConnectionFactory.CreateTransient(String entityConnectionString, IDataLoader dataLoader)   
at Effort.EntityConnectionFactory.CreateTransient(String entityConnectionString)   

Removing the Precision attribute from sequence_num column in the SSDL and re-running the tools for Entity does not resolve the error. The only way to get rid of the exception and get Effort to load the model is to remove the sequence_num column from the edmx model entirely.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.