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

Created Unassigned: Argument Exception on EntityConnectionstring [762]

$
0
0
When using the Effort.EntityConnectionFactory.CreateTransient(string connString, IDataLoader loader) overload, currently getting an Argument Exception "Format of the initialization string does not conform to specification starting at index 80." with the following Stacktrace:

at System.Data.Entity.Core.EntityClient.Internal.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, String& keyname, String& keyvalue)
at System.Data.Entity.Core.EntityClient.Internal.DbConnectionOptions.ParseInternal(IDictionary`2 parsetable, String connectionString, IList`1 validKeywords)
at System.Data.Entity.Core.EntityClient.Internal.DbConnectionOptions..ctor(String connectionString, IList`1 validKeywords)
at System.Data.Entity.Core.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
at System.Data.Entity.Core.EntityClient.EntityConnection..ctor(String connectionString)
at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel()
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 Namespace.SaveMethodName(Object obj, DbContext ctxt) in \\192.168.1.146\public\MS\Monitoring Dashboard\MediaDashboard\MediaDashboard.Persistence\Storage\AzureDataAccess.cs:line x

Also tried just the Entity connectionstring, and got a similar error:
"The given path's format is not supported."

These are MS Azure based connections, and should behave the same as any other SQL server connention

New Post: Getting a fresh in memory database for each test

$
0
0
tamasflamich wrote:
....
I also added a new API that allows to simply clear the database tables. I will share the details soon.
Hi, unfortunately I cannot find it anywhere, is this published already, can you share please? I'm interested in an easy way to clear the data from the database, so I do not need to create it each time. The schema is not small and it takes a while to create, so I would prefer to build it once and just clear the data.

New Post: An error occurred while preparing the command definition. Not supported DbCommandTree type

$
0
0
Has anyone seen this error. I get it while calling a stored procedure. Any help would be greatly appreciated.

An error occurred while preparing the command definition. Not supported DbCommandTree type.

Call Stack:
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory)
at System.Data.Entity.Core.EntityClient.EntityCommand.CreateCommandDefinition()
at System.Data.Entity.Core.EntityClient.EntityCommand.TryGetEntityCommandDefinitionFromQueryCache(EntityCommandDefinition& entityCommandDefinition)
at System.Data.Entity.Core.EntityClient.EntityCommand.GetCommandDefinition()
at System.Data.Entity.Core.Objects.ObjectContext.CreateFunctionObjectResult[TElement](EntityCommand entityCommand, ReadOnlyCollection1 entitySets, EdmType[] edmTypes, ExecutionOptions executionOptions)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass47
1.<ExecuteFunction>b__46()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass47
1.<ExecuteFunction>b__45()
at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteFunction[TElement](String functionName, ExecutionOptions executionOptions, ObjectParameter[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteFunction[TElement](String functionName, MergeOption mergeOption, ObjectParameter[] parameters)

Thanks!

New Post: How to directly modify underlying nmemory database

$
0
0
Hi, We have a EF6 code first model which uses a boolean discriminator to implement soft delete. The boolean column is set up in OnModelCreating like this...
    modelBuilder.Entity<MyEntity>()
        .Map(m => m.Requires("SoftDeleted").HasValue(false))
        .Ignore(m => m.SoftDeleted);
So you can see that the SoftDeleted property is not directly accessible. In normal use against the real database we set SoftDeleted using an SQL update. For testing we need to do the equivalent for NMemory. Is there a way to do this?

Commented Unassigned: System.InvalidOperationException was unhandled by user code HResult=-2146233079 Message=Sequence contains no matching element [760]

$
0
0
Attempting to add test data like this using EF 6.1.3:

```
using System;
using System.Data.Entity.Migrations;
using Cssd.IT.PortalIntegration.POCO.SISMid.BO;

namespace Cssd.IT.PortalIntegration.DataAccessTest
{
public class SISMidDataAccessTestData
{
public static void AddTestData(ISISMidDbContext context)
{
context.LookupGrade.AddOrUpdate(new LookupGrade { GradeCode = -1, Grade = "PK4" });
context.LookupGrade.AddOrUpdate(new LookupGrade { GradeCode = 0, Grade = "00" });
context.LookupGrade.AddOrUpdate(new LookupGrade { GradeCode = 1, Grade = "01" });
context.LookupGrade.AddOrUpdate(new LookupGrade { GradeCode = 6, Grade = "06" });
context.LookupGrade.AddOrUpdate(new LookupGrade { GradeCode = 9, Grade = "09" });
context.LookupGrade.AddOrUpdate(new LookupGrade { GradeCode = 12, Grade = "12" });
}
}
}
```

Here is the LookupGrade class:

```
namespace Cssd.IT.PortalIntegration.POCO.SISMid.BO
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
using Cssd.IT.PortalIntegration.POCO.School.BO;

public partial class LookupGrade : IImportBusinessKey
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int GradeCode { get; set; }

[Required]
[StringLength(3)]
public string Grade { get; set; }

[Column(TypeName = "smalldatetime")]
public DateTime? CC_SISMIDRefreshDate { get; set; }

public string ImportBusinessKey
{
get { return this.GradeCode.ToString(); }
}
}
}

```

This is my database table, where GradeCode is an integer non-identity primary key:

```
/****** Script for SelectTopNRows command from SSMS ******/
SELECT TOP 1000 [GradeCode]
,[Grade]
,[CC_SISMIDRefreshDate]
FROM [CC_SISMID].[dbo].[LookupGrade]
```

When the first AddOrUpdate executes, receiving this exception:

```
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Sequence contains no matching element
Source=System.Core
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.Migrations.DbSetMigrationsExtensions.GetKeyProperties[TEntity](Type entityType, InternalSet`1 internalSet)
at System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](IDbSet`1 set, TEntity[] entities)
at Cssd.IT.PortalIntegration.DataAccessTest.SISMidDataAccessTestData.AddTestData(ISISMidDbContext context) in c:\DevProjects\IT_Portal\Source\PortalIntegration\Cssd.IT.PortalIntegration.DataAccessTest\SISMidDataAccessTestData.cs:line 12
at Cssd.IT.PortalIntegration.DataAccessTest.SISMidDataAccessTest.Setup() in c:\DevProjects\IT_Portal\Source\PortalIntegration\Cssd.IT.PortalIntegration.DataAccessTest\SISMidDataAccessTest.cs:line 27
InnerException:
```

Does anyone have any suggestions? The above error occurs only when attempting to test with Effort, in code-first entity framework mode. When the unit test is run against SQL Server, or if we run in database-first entity framework mode, it works fine. TIA.
Comments: One thing to do is to look at the inner exception and see if there are any validation errors reported. This helped me when I failed to spot a 'required' field.

Reviewed: Effort 1.0.0 (Nov 24, 2015)

$
0
0
Rated 5 Stars (out of 5) - I haven't looked at all the features yet, but this is the first software where I can use the original DbContext and test my DbSets in memory. All other examples that I saw, inclusive the FakeDbSet that Microsoft proposed couldn't handle adding an entity with a collection of other entities which would normally result in a set of items with Foreign Keys. Example: suppose a blog with a collection of Posts. Normaly each post would be in a different DbSet<Post>, each Post with a foreign key to the Blog it belongs to. If you create a blog with a collections of Posts, and add the blog to the DbSet<Blog>, then Context.SaveChanges would automatically take care that the Posts were added to the DbSet<Post>. Alas all examples I saw didn't do that, inclusive several FakeDbSet that are distributed as Nuget Packages. This is the first package that really lets me use my original DbContext with the original DbSet, for in-memory unit testing. I can even use the full Repository / Unit-of-work patterns without changing anything for my unit tests. Bravo!

Commented Unassigned: Coupled issue between NMemory and Effort with Transaction [719]

$
0
0
The current project that I am on is using the unit of work pattern with the transaction stored in the unit of work.

For some reason during the test, the unit gets created and the transaction started. A save operation is called on an entity, and then I try to read the entity. The save operation happens in a matter of a couple of MS. However, the next operation I have is a read operation where I do a single or default with the saved entities Id, and the operation takes more than 14 seconds. Then when the UOW tries to dispose, the commit fails due to a timedout transaction. Is there any way to extend the timeout for the transaction with NMemory? Is there any reason why a subsequent read would result in a long operation?
Comments: I ran into similar issue, and I have attached the code sample herewith showing the test fails (may be not because of timeout, but unable to fetch the recently saved changes), appreciate if you can suggest a solution or point out if there is anything wrong with the usage.

Commented Unassigned: Using SqlFunctions [722]

$
0
0
I find in a test using effort that uses a query using SqlFunctions, I get an exception. I can see why this would be - SqlFunctions being SQL specific and Effort looking to remain database agnostic. But wonder if anyone has any suggestions to get around this?

Thanks

Andy
Comments: How could we do setup on init or write test, when some of the repository code that we intend to test using effort makes call to SQL functions or user defined functions that exist in actual DB but not in nmemory, is there a standard practice to create alternate deterministic function equivalents in DB during init?

Created Unassigned: Invalid format arguments order in Effort.Internal.DbManagement.Schema.DbTableInfo for ExceptionMessages.EntityPropertyAssignFailed [763]

$
0
0
Error displayed:
> Effort.Exceptions.EffortException: An unhandled exception occurred while trying to assign value '[null]' to __Property'System.Int64'__ of type __'Id'__ during entity initialization for table 'ParameterCollections'

Probably means:
> Effort.Exceptions.EffortException: An unhandled exception occurred while trying to assign value '[null]' to __Property 'Id'__ of type __'System.Int64'__ during entity initialization for table 'ParameterCollections'

Created Unassigned: NUnit, first run after a build, slow [764]

$
0
0
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?

New Post: Can Effort be used with nested transactions?

$
0
0
For future reference; for transient entities, I solved my problems by faking the EntityConnection instead of the ObjectContext,.
The problem with timeouts on disposing the transactions when using persistent connections still applies though:
using System;
using System.Data.EntityClient;
using System.Linq;
using System.Transactions;
using EffortIsolationDataLayer;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace EffortIsolationLevelTest
{
    [TestClass]
    public class EffortIsolationLevelTests
    {
        private EntityConnection _connection;

        [TestInitialize]
        public void InitTests()
        {
            _connection = Effort.EntityConnectionFactory.CreateTransient("name=NorthwindEntities");
            //Using persistent still causes timeouts on disposing
            //_connection = Effort.EntityConnectionFactory.CreatePersistent("name=NorthwindEntities");
        }

        [TestMethod]
        public void ShouldBeAbleToWriteInNestedTransactions()
        {
            using (var outerScope = CreateTransactionScope())
            {
                using (var outerContext = CreateObjectContext())
                {
                    var outerTransactionIdentifier = Transaction.Current.TransactionInformation.LocalIdentifier;
                    CreatePhoneNumberTypeAndAddToContext(outerContext, "Some type of phone number");
                    using (var innerScope = CreateTransactionScope())
                    {
                        using (var innerContext = CreateObjectContext())
                        {
                            Assert.AreNotEqual(outerTransactionIdentifier,
                                Transaction.Current.TransactionInformation.LocalIdentifier,
                                "Should use separate transactions");
                            CreatePhoneNumberTypeAndAddToContext(innerContext, "Some other type of phone number");
                        }
                        innerScope.Complete();
                    }
                }
                outerScope.Complete();
            }

            using (var finalScope = CreateTransactionScope())
            {
                using (var finalContext = CreateObjectContext())
                {
                    Assert.AreEqual(2, finalContext.PhoneNumberTypes.Count(),
                        "Final transaction should be able to read data from the other completed transactions");
                }
            }
        }

        private static void CreatePhoneNumberTypeAndAddToContext(NorthwindEntities context, string name)
        {
            var type = new PhoneNumberType() {Name = name, ModifiedDate = DateTime.Now};
            AddToContextAndSaveChanges(context, type);
        }

        private static void AddToContextAndSaveChanges(NorthwindEntities context, PhoneNumberType phoneNumberType)
        {
            context.AddToPhoneNumberTypes(phoneNumberType);
            context.SaveChanges();
        }

        private static TransactionScope CreateTransactionScope()
        {
            return new TransactionScope(TransactionScopeOption.RequiresNew,
                new TransactionOptions() {IsolationLevel = IsolationLevel.ReadCommitted, Timeout = new TimeSpan(0, 0, 5)});
        }

        private NorthwindEntities CreateObjectContext()
        {
            return new NorthwindEntities(_connection);
        }
    }

}

Reviewed: Effort 1.0.0 (dec 23, 2015)

$
0
0
Rated 5 Stars (out of 5) - extremely simple setup to accomplish a very complicated task, thank you, thank you

New Post: Relationship issues

$
0
0
So I'm trying to do something that I would think is fairly straightforward. I have an entity (MasterOrder) that has children (Orders). I am loading the data / relationship in via the CSV loader.

When I attempt to run a MasterOrder through a processing method though, and it attempts to loop through the Orders, there are none there.

Which is weird because as soon as I add a line like
var orders = _db.Orders.ToList();
in before calling the processing method, they ARE there, both in the "orders" variable via debug and in the normal loop where they weren't showing up before.

All fairly normal EF setup on all of this, nothing special.

Any idea why I would be seeing this? Only caveats I have:
  1. The MasterOrder processing method is async and is awaited.
  2. Test method itself is async.
  3. Test runner is NUnit.
  4. On DbContext we have LazyLoadingEnabled set to false
I have a suspicion its that last one, but just wanted to make sure I understood what the issue is.

New Post: The 'Instance' member of the Entity Framework provider type 'Effort.Provider.EffortProviderFactory, Effort,...' did not return an object that inherits from 'System.Data.Entity.Core.Common.DbPr

$
0
0
I am trying to set up Effort with EF6. I downloaded the Effort.EF6 Nuget package which automatically installed EF6.0.02. After all the initial setups, when I call the MyAppContext's contructor, I get this error.

The 'Instance' member of the Entity Framework provider type 'Effort.Provider.EffortProviderFactory, Effort, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6a46696d54971e6d' did not return an object that inherits from 'System.Data.Entity.Core.Common.DbProviderServices'


Please let me know What goes missing here.

New Post: Relationship issues

$
0
0
Number 4 is your problem. When you say LazyLoadingEnabled = false, it doesnt mean that it is eager loaded. It means that, do not load (relationships) at all.

There is no way until EF6 to eager load the complete DB. I am also facing a similar problem where each of my test case is lazy loading from CSV and creating a lag in the test cases.

New Post: Cannot use the downloaded the source code.

$
0
0
When i try to use the Effort Dll compiled from the Source code, i get an error stating EffortProviderServices is not of type DBProviderServices. Am I missing something?

I am trying to improve the dataloader time (CSVDataLoader). But cant get it to merge with my application.

Created Unassigned: Using Migrations with Effort [765]

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

New Post: Cannot use the downloaded the source code.

$
0
0
Never mind. Solved the problems by referencing EF from Nuget.

Commented Unassigned: Have to manually update context class every time [761]

$
0
0
When using Effort, it requires an interface to be used in the context class, such as in MyAppContext.cs:

```
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace TestingEf.Data.Entities
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Common;

public partial class MyAppContext : DbContext, IMyAppContext
{
/// <summary>
/// Constructs a new context instance with the default connection string.
/// </summary>
public MyAppContext()
: base("name=MyAppContext")
{
this.Configuration.LazyLoadingEnabled = false;
}

/// <summary>
/// Constructs a new context instance using the given string as the name or connection
/// string for the database to which a connection will be made. See the DbContext class
/// remarks for how this is used to create a connection.
/// </summary>
/// <param name="nameOrConnectionString">Either the database name or a connection string.</param>
public MyAppContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
this.Configuration.LazyLoadingEnabled = false;
}

/// <summary>
/// Constructs a new context instance using the given DbConnection.
/// The given connection will be disposed when this instance is disposed
/// </summary>
/// <param name="connection">The connection to create the context with</param>
public MyAppContext(DbConnection connection)
: base(connection, true)
{
this.Configuration.LazyLoadingEnabled = false;
}

public IDbSet<Product> Products { get; set; }
public IDbSet<ProductTag> ProductTags { get; set; }
public IDbSet<Tag> Tags { get; set; }

}
}

```

The problem is, every time I update the EDMX model from changes in the SQL Server database, it also re-generates the MyAppContext.cs file, so the IMyAppContext gets blown away:

[Update Model](http://imgur.com/HHvZ2Vz)

Is there any way to resolve this issue so that I don't have to re-add the IMyAppContext and the overloaded constructors every time I update the EDMX model from the database?
Comments: You can split your code into two files. So you need to create another new file with the following code: namespace TestingEf.Data.Entities { partial class MyAppContext : DbContext, IMyAppContext { /// <summary> /// Constructs a new context instance using the given DbConnection. /// The given connection will be disposed when this instance is disposed /// </summary> /// <param name="connection">The connection to create the context with</param> public MyAppContext(DbConnection connection) : base(connection, true) { this.Configuration.LazyLoadingEnabled = false; } } }

New Post: Performance Problems with inheritance

$
0
0
I am seeing a drastic performance issue with Inherited Entities. (Table-Per-Type) mapping.
The lambda expression generated for 7 children runs to 140 lines. It took around 43 seconds to get a single Base record. Are you aware of this problem, if so, is there any work around for this?
Viewing all 111 articles
Browse latest View live


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