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

New Post: Database.ExecuteSqlCommand Not Supported Exception

$
0
0
Hi there,

I am trying to test a method with the following line in it:

DB.Database.ExecuteSqlCommand(query);

Where query is a delete command like "DELETE FROM Image WHERE StockId = 2"

In production this line works as expected, however, within the context of our test project (which uses Effort), this line throws the exception 'Specified method is not supported.'

Is this a known limitation? Is there a workaround? The reason we are doing deletes this way rather than via .RemoveRange is to avoid having to first query the database to identify the records to delete, and therefore reduce database load.

Stack trace is as follows:
at Effort.Provider.EffortCommand.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,TInterceptionContext,TResult](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.Objects.ObjectContext.<>c__DisplayClass59.<ExecuteStoreCommand>b__58()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass59.<ExecuteStoreCommand>b__57()
   at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreCommand(TransactionalBehavior transactionalBehavior, String commandText, Object[] parameters)
   at System.Data.Entity.Internal.InternalContext.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
   at System.Data.Entity.Database.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
   at System.Data.Entity.Database.ExecuteSqlCommand(String sql, Object[] parameters)

New Post: Many ".Include"'s yields 5 minute query time or longer.

$
0
0
I am trying to do some unit tests where I have the following:
        investment = db.Investment
            .Include(e => e.Positions.Select(p => p.Transactions))
            //.Include(e => e.Positions.Select(p => p.InvestmentCarry))
            .Include(e => e.RelatedInvestments)
            .Include(e => e.PrivateInvestment)
            .Include(e => e.CoInvestment)
            .FirstOrDefault(e => e.Id == id)
            ;
The time it takes for Effort to execute this is 5 or more minutes. I have another LINQ query that is similar that takes 14 minutes on our build server.

Any ideas? Does Effort need to be adjusted somehow? Maybe I need to reconsider how I've set up my query, although in a database environment it executes quickly.

Any suggestions?

New Post: Is there a way to view in memory tables

$
0
0
I have tried to load my tables with csv files, everything seems to be okay but when I query my dbset on the context in my test there appears to be no data.

I didn't get any errors initializing the context so I assume the data load was okay, how can I tell what has been loaded or if there were any issues in this process etc?

Thanks

Commented 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?
Comments: I'm getting the exact same behavior and frankly it's a pain. Makes it hard for me to justify using Effort in the system I'm working on. Are there any configuration changes or other tricks that can make Effort / NMemory start up faster?

Commented Unassigned: "Argument types do not match" error with Nullable DateTime ?? Operator [748]

$
0
0
I have a problem when querying a condition using the ?? Operator on a Nullable<DateTime> property of my entity.

"result1" and "result2" work fine. "result3" throws an "Argument types do not match" exception.

var result1 = context.Prospect_Task.Count(pt => (pt.sortOrder ?? 0) > 1);
var result2 = context.Prospect_Task.Count(pt => pt.dueDate < DateTime.Now);
var result3 = context.Prospect_Task.Count(pt => (pt.dueDate ?? DateTime.MaxValue) < DateTime.Now);

Perhaps it is related to this earlier issue:

https://effort.codeplex.com/workitem/701

The stacktrace is below.

System.Data.Entity.Core.EntityCommandExecutionException was unhandled by user code
HResult=-2146232004
Message=An error occurred while executing the command definition. See the inner exception for details.
Source=EntityFramework
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.Single[TSource](IEnumerable`1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3[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.Count[TSource](IQueryable`1 source, Expression`1 predicate)
at QuickScreenAPITest.ProspectTests.ProspectsContext_CheckDashboardActiveProspects_Success() in c:\Projects\WebServices\QuickScreenAPI\QuickScreenAPITest\ProspectTests.cs:line 501
InnerException: System.ArgumentException
HResult=-2147024809
Message=Argument types do not match
Source=System.Core
StackTrace:
at System.Linq.Expressions.Expression.Condition(Expression test, Expression ifTrue, Expression ifFalse)
at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbCaseExpression expression)
at System.Data.Entity.Core.Common.CommandTrees.DbCaseExpression.Accept[TResultType](DbExpressionVisitor`1 visitor)
at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbExpression expression)
at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbComparisonExpression expression)
at System.Data.Entity.Core.Common.CommandTrees.DbComparisonExpression.Accept[TResultType](DbExpressionVisitor`1 visitor)
at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbExpression expression)
at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbFilterExpression expression)
at System.Data.Entity.Core.Common.CommandTrees.DbFilterExpression.Accept[TResultType](DbExpressionVisitor`1 visitor)
at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbExpression expression)
at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbGroupByExpression expression)
at System.Data.Entity.Core.Common.CommandTrees.DbGroupByExpression.Accept[TResultType](DbExpressionVisitor`1 visitor)
at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbExpression expression)
at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbProjectExpression expression)
at System.Data.Entity.Core.Common.CommandTrees.DbProjectExpression.Accept[TResultType](DbExpressionVisitor`1 visitor)
at Effort.Internal.DbCommandTreeTransformation.TransformVisitor.Visit(DbExpression expression)
at Effort.Internal.CommandActions.QueryCommandAction.ExecuteDataReader(ActionContext context)
at Effort.Provider.EffortEntityCommand.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)
InnerException:

Comments: Is the solution in TransformVisitor.Case.cs proposed by Mattias Koerner above in any of the Effort.EF6 releases? Thanks,

Created Unassigned: CSVTool download missing [767]

$
0
0
Following [download](http://effort.codeplex.com/releases/) links, I don't see the tool listed on the right side downloads, nor as a NuGet package from inside VS.NET.

Any pointers in the right direction or can it be restored if missing?

Edited Unassigned: System.Data.Entity.Infrastructure.UnintentionalCodeFirstException was unhandled by user code [759]

$
0
0
When I attempt to run a unit test using Effort in database-first mode, this is the exception I'm getting:

```
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException was unhandled by user code
HResult=-2146233079
Message=The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
Source=Cssd.IT.PortalIntegration.DataAccess
StackTrace:
at Cssd.IT.PortalIntegration.DataAccess.HR.Dao.HRADDbContext.OnModelCreating(DbModelBuilder modelBuilder) in c:\DevProjects\IT_Portal\Source\PortalIntegration\Cssd.IT.PortalIntegration.DataAccess\HR.Dao\HRModel.Context.cs:line 50
at System.Data.Entity.DbContext.CallOnModelCreating(DbModelBuilder modelBuilder)
at System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
InnerException:
```

This is the line of code that throws the exception in the DbContext:

```
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
```

The above exception should not be removed in database-first mode, since it should never be called in that mode because all of the mappings are in the EDMX file. The OnModelCreating should only be called in code-first EF mode to build the mappings between the database and the source code. See https://blog.oneunicorn.com/2012/02/26/dont-use-code-first-by-mistake/

Does anyone have any suggestions? TIA.

New Post: Stored Procedures & Direct SQL

$
0
0
Tamas:

I can appreciate that your code would not know how to "do" all of the steps within the stored proc. But couldn't you create a stub that would allow the user to define what comes back to fake the response, not actually execute code?

i.e.
IDataLoader loader = new SomeMagicLoaderToPrePopulateMyStoredProcResponses();
using (MyEntities ctx = Effort.ObjectContextFactory.CreateTransient<MyEntities>(loader))
{
    List<usp_MyStoredProc_Response> response = ctx.usp_MyStoredProc(a, b, c);
} 
The variables A, B and C would be ignored, but there because the call to MyStoredProc requires them. However, the loader has already PRE-DEFINED the data that will come back on this call so that we can mock-out what might happen in specific scenarios.

Just a thought. Is this even possible?

Created Unassigned: Operation is not valid due to the current state of the object., when establishing the connection [768]

$
0
0
Getting this error when try to esablish a connection
Message "Operation is not valid due to the current state of the object." string
Source "Effort" string
StackTrace " at Effort.Provider.EffortConnection.get_DbManager()" string

Created Unassigned: Problem with group by data aggregation. [769]

$
0
0
I have a problem with group by data aggregation. Bellow you can see a code that works fine with mssql database, but when i try to run unit test using Effort framework, it gives me an error "Incorrect number of arguments for constructor".
What is interesting, when I cut from "select" clause any 2 summary variables, it works fine.
I assume that Effort has a limitation for maximum 6 agregation column.
Am I right? Will it be corrected in future?

Linq query that raise an error:
```
var detailValues = (from detail in u.PromoActionPageDetails.Find(d => d.PromoActionId == promoAction.Id)
group detail by detail.PromoActionId into value
select new
{
PromoActionId = value.Key,
TurnoverEstimation = value.Sum(v => v.PlannedQnty * v.PriceSaleAction),
TurnoverReality = value.Sum(v => v.AdjustedQtty * v.PriceSaleAction),
MarginEstimation = value.Sum(v => v.PlannedQnty * v.PriceSaleAction / v.PricePurchaseAction),
MarginReality = value.Sum(v => v.AdjustedQtty * v.PriceSaleAction / v.PricePurchaseAction),
GrossProfitEstimation = value.Sum(v => v.PlannedQnty * (v.PriceSaleAction - v.PricePurchaseAction)),
GrossProfitReality = value.Sum(v => v.AdjustedQtty * (v.PriceSaleAction - v.PricePurchaseAction)),
ContributionEstimation = value.Sum(v => v.SupplierContributionAmount),
ContributionReality = value.Sum(v => v.SupplierContributionAmount)
}).FirstOrDefault();
```

New Post: Many ".Include"'s yields 5 minute query time or longer.

$
0
0
Anyone figure out a solution for this? Having same issue. Single include works fine. Adding a second include times out. Either seems like a major limitation of the library or else we're doing something incorrectly. Either way would be nice to document a solution.

Commented Unassigned: Problem with group by data aggregation. [769]

$
0
0
I have a problem with group by data aggregation. Bellow you can see a code that works fine with mssql database, but when i try to run unit test using Effort framework, it gives me an error "Incorrect number of arguments for constructor".
What is interesting, when I cut from "select" clause any 2 summary variables, it works fine.
I assume that Effort has a limitation for maximum 6 agregation column.
Am I right? Will it be corrected in future?

Linq query that raise an error:
```
var detailValues = (from detail in u.PromoActionPageDetails.Find(d => d.PromoActionId == promoAction.Id)
group detail by detail.PromoActionId into value
select new
{
PromoActionId = value.Key,
TurnoverEstimation = value.Sum(v => v.PlannedQnty * v.PriceSaleAction),
TurnoverReality = value.Sum(v => v.AdjustedQtty * v.PriceSaleAction),
MarginEstimation = value.Sum(v => v.PlannedQnty * v.PriceSaleAction / v.PricePurchaseAction),
MarginReality = value.Sum(v => v.AdjustedQtty * v.PriceSaleAction / v.PricePurchaseAction),
GrossProfitEstimation = value.Sum(v => v.PlannedQnty * (v.PriceSaleAction - v.PricePurchaseAction)),
GrossProfitReality = value.Sum(v => v.AdjustedQtty * (v.PriceSaleAction - v.PricePurchaseAction)),
ContributionEstimation = value.Sum(v => v.SupplierContributionAmount),
ContributionReality = value.Sum(v => v.SupplierContributionAmount)
}).FirstOrDefault();
```
Comments: Any news on this? I just updated the version of Effort I was using and now several unit tests are failing because of this issue.

New Post: Effort fails to detect REFERENCE constraint

$
0
0
So i have this model where i have the relation table connecting to two people
 public class People {
...
        public virtual ICollection<Relation> Relation { get; set; }
        public virtual ICollection<Relation> Relation2 { get; set; }
        public virtual ICollection<FollowUp> FollowUps { get; set; }
...
}
    public class Relation {
        [Key]
        [Column(Order = 0)]
        public int personRef1Id { get; set; }
        [Key]
        [Column(Order = 1)]
        public int personRef2Id { get; set; }
        public int RelationTypeRefId { get; set; }
        public virtual People person1 { get; set; }
        public virtual People person2 { get; set; }
        public virtual RelationType Relationtype { get; set; }
    }
with the override
  protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            modelBuilder.Entity<Relation>()
                .HasKey(i => new { i.personRef1Id, i.personRef2Id });

            modelBuilder.Entity<Relation>()
                .HasRequired(i => i.person1)
                .WithMany(i => i.Relation)
                .HasForeignKey(i => i.personRef1Id)
                .WillCascadeOnDelete(false); //the one

            modelBuilder.Entity<Relation>()
                .HasRequired(i => i.person2)
                .WithMany()
                .HasForeignKey(i => i.personRef2Id)
                .WillCascadeOnDelete(false); //the one
}
WillCascadeOnDelete is false since it will not work because of multiple cascade paths.

In any case, here is the problem.

When targeting the actual database if i try to delete a person that has relations i get:
{"The DELETE statement conflicted with the REFERENCE constraint \"FK_dbo.Relations_dbo.People_personRef1Id\". The conflict occurred in database \"prm.crmcontext\", table \"dbo.Relations\", column 'personRef1Id'.\r\nThe statement has been terminated."}
However when doing the same in my test (this particular one has 3 people and 1 relation between 2 of them)
context.Relations.Add(newRelation);
                context.SaveChanges();
                Assert.AreEqual(1, context.Relations.Count(), "Relations was not added properly");

                context.People.Remove(person1);
                context.SaveChanges();
                Assert.AreEqual(2, context.People.Count(), "People were not deleted properly");
                Assert.AreEqual(0, context.Relations.Count();
It works just fine.

New Post: Is Effort.EF6 supported with EF 6.1.3?

$
0
0
I am using Effort.EF6 with EF 6.1.3.

Is it supported with EF 6.1.3 ?

I am unable to add entries to the entities, Add() or AddRange() methods failing with this exception: "System.InvalidOperationException : Sequence contains no matching element"

Stack Trace:

at System.Linq.Enumerable.Single[TSource](IEnumerable1 source, Func2 predicate)
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.<>c__DisplayClass4.<Configure>b__3(Tuple2 pm)
at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable
1 ts, Action1 action)
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, ICollection1 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.InternalSet1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet
1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet1.AddRange(IEnumerable entities)
at System.Data.Entity.DbSet
1.AddRange(IEnumerable`1 entities)

Created Unassigned: EF6 Projection Query / Context Persistence Issue [770]

$
0
0
We've written a generic repository pattern for our project and within our Get method, we are using a projection query to shape the query that ultimately gets run on our data store so we can avoid SELECT * FROM [Table]. However, when we're unit testing our repository, we're running into an issue where when the query is executed with the projection, the entity object(s) that get returned aren't being persisted to our underlying context. We are getting the data we need out of the Effort data store, but it not persisting to the context caused a false positive passing test as a live dbConnection does persist it.

Here is our get method:

```
public IEnumerable<OEntity> Get<OEntity>(
Expression<Func<TEntity, OEntity>> columns,
out int totalRecords,
out int actualPage,
Expression<Func<TEntity, bool>> filter = null,
List<SearchSortParameters> sortParams = null,
List<Expression<Func<TEntity, object>>>
includeProperties = null,
int? page = 1,
int? pageSize = 50)
{
if (page.HasValue)
{
if (page < 1)
page = 1;
}

if (pageSize.HasValue)
{
if (pageSize < 1)
pageSize = 1;

if (pageSize > 50)
pageSize = 50;
}

IQueryable<TEntity> query = _dbSet;

if (includeProperties != null)
includeProperties.ForEach(i => query.Include(i));

if (filter != null)
query = query.Where(filter);

totalRecords = query.Count();

var skip = 0;

if (page.HasValue && pageSize.HasValue)
{
skip = (page.Value - 1) * pageSize.Value;

if (skip < totalRecords)
{
actualPage = page.Value;
}
else
{
var remainder = (totalRecords % pageSize.Value);
skip = totalRecords - remainder;

if (remainder == 0)
actualPage = totalRecords / pageSize.Value;
else
actualPage = (totalRecords / pageSize.Value) + 1;
}
}
else
actualPage = 1;

if (sortParams != null && sortParams.Count > 0)
{
for (int i = 0; i < sortParams.Count; i++)
{
var sortParam = sortParams[i];

if (i == 0)
{
switch (sortParam.direction.ToUpper())
{
case "ASC":
query = query.OrderBy(sortParam.column, "OrderBy");
break;
case "DESC":
query = query.OrderByDescending(sortParam.column, "OrderByDescending");
break;
}
}
else
{
switch (sortParam.direction.ToUpper())
{
case "ASC":
query = query.OrderBy(sortParam.column, "ThenBy");
break;
case "DESC":
query = query.OrderByDescending(sortParam.column, "ThenByDescending");
break;
}
}
}
}

if (page != null && pageSize != null)
query = query
.Skip(skip)
.Take(pageSize.Value);

var securityHelper = new SecurityHelper();
if (typeof(IReadAuditable).IsAssignableFrom(typeof(TEntity)))
{
if (securityHelper.IsAuthenticated() && securityHelper.HasClaim(Constants.CustomClaimTypes.UserId.GetStringValue()))
{
var userId =
int.Parse(
securityHelper.GetClaimValue(Constants.CustomClaimTypes.UserId.GetStringValue()).First());

foreach (TEntity item in query)
{
_auditLog.Insert(null, new AuditLog
{
Action = "Read",
UserId = userId,
AuditDate = DateTime.Now,
RecordId = string.Join(",", ((System.Data.Entity.Infrastructure.IObjectContextAdapter)_context).ObjectContext.ObjectStateManager.GetObjectStateEntry(item).EntityKey.EntityKeyValues.Select(x =>
$"{x.Key}:{x.Value}")),
TableName = ObjectContext.GetObjectType(item.GetType()).Name
});
}
}
}

//var entities = query.ToList();
return query.Select(columns).ToList(); //This line being executed with Effort isn't persisting the returned entities to the underlying dbset and context, but it is returning the data.
}
```

If I were to uncomment this line "var entities = query.ToList();" to execute a non-projecting query against the db store, the data is persisted to the dbset and context as expected. This line isn't necessary when we run the same code above against non-Effort dbConnection.

Any help would be greatly appreciated because we really don't want to have to remove projections or have to put in hard-coded handling for our tests.

New Post: Help needed - stuck with ModelBuilder issues (class properties...)

$
0
0
I can't get effort to build the database in my unit-test project.
The Entity Configurations work fine with Entity Framework.

My abstract class 'EventBase' contains a ValueObject 'Duration'.
Entity Framework accepts this setup without problems.
The solution builds fine, but when I run or debug my unit test, it fails

System.InvalidOperationException: Sequence contains no matching element

When I test with a real database, the tables get created fine.
SoccerTraining (
  Id int,
  Description nvarchar(max),
  Start datetime,
  Duration_Seconds bigint)
But Effort doesn't seem to handle the class property properly. Am I overseeing something, or is this a bug?
public class Duration : IEquatable<Duration>
{
    public TimeSpan? Length { get; set; }
    public long? Seconds { get; set; }
    public bool Equals(Duration other);
    public static implicit operator TimeSpan? (Duration duration);
    public static implicit operator Duration(TimeSpan timeSpan);
    public static implicit operator Duration(TimeSpan? timeSpan);
}

public abstract class EventBase : EntityBase
{
    public DateTime Start { get; set; }
    public Duration Duration {get; set; }
    public RecurrenceRule RecurrenceRule { get; set; }
}

public class SoccerTraining : EventBase
{
    public string Description { get; set; }
    //---
}


public class SoccerTrainingMap : EntityMapBase<SoccerTraining>
{
    public SoccerTrainingMap()
    {
        ToTable("SoccerTrainings");
        Ignore(st => st.RecurrenceRule);
        //---
    }
}

public class DurationMap: EntityMapBase<Duration>
{
    public DurationMap()
    {
        Ignore(d => d.Length);
    }
}

public class EfSoccerModelDbContext : BaseDbContext, ISoccerModelDbContext
{
    //---
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        
        modelBuilder.Configurations.Add(new SoccerTrainingMap());
    }
}

public abstract class BaseDbContext : DbContext, IDbContext
{
    private readonly List<Object> _objectSetCache = new List<Object>();
    
    protected BaseDbContext(string connectionString) : base(connectionString)
    { }

    protected BaseDbContext(DbConnection connection) :base(connection, true)
    { }
    
    public IDbSet<TEntity> GetDbSet<TEntity>() where TEntity : class
    {
        var set = _objectSetCache.OfType<DbSet<TEntity>>().FirstOrDefault();
        if (set == null)
        {
            set = Set<TEntity>();
            _objectSetCache.Add(set);
        }
        return set;
    }
    
    //---
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Configurations.Add(new DurationMap());     
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    }
}

public class EffortDbContext : EfSoccerModelDbContext
{
    public EffortDbContext(DbConnection dbConnection) : base(dbConnection)
    {
    }

    public void ProvideData<TEntity>(IEnumerable<TEntity> data) where TEntity : class
    {
        var dbSet = this.GetDbSet<TEntity>();
        foreach (var item in data)
        {
            dbSet.Add(item);
        }
    }
}

[TestClass]
public class SoccerTrainingUnitTests
{
    private EffortDbContext _dbContext;
    private ISoccerTrainingRepository _soccerTrainingRepository;

    [TestInitialize]
    public void MyTestInitialize()
    {
        Effort.Provider.EffortProviderConfiguration.RegisterProvider();
        var connection = Effort.DbConnectionFactory.CreateTransient();
        using (var dbContext = new EffortDbContext(connection))
        {
            dbContext.Database.Initialize(true);
            var soccerTrainings = GetSoccerTrainingData();
            dbContext.ProvideData(soccerTrainings);
            dbContext.SaveChanges();
        }
        
        _dbContext = = new EffortDbContext(connection);
        
        var dbContextFactoryMock = new Mock<IDbContextFactory>();
        dbContextFactoryMock.Setup(x => x.Create<ISoccerModelDbContext>()).Returns(_dbContext);

        _soccerTrainingRepository = new SoccerTrainingRepository(dbContextFactoryMock.Object);
    }
    
    [TestMethod]
    public void SoccerTrainingDomainService_BlahBlahBlah()
    {
        var soccerTrainings = _soccerTrainingRepository.GetAllSoccerTrainings();
        
        Assert.AreEqual(3, soccerTrainings.Count());
    }
    
    private IEnumerable<SoccerTraining> GetSoccerTrainingData()
    {
        yield return SoccerTraining.CreateRandom();
        yield return SoccerTraining.CreateRandom();
        yield return SoccerTraining.CreateRandom();
    }
}

New Post: Help needed - stuck with ModelBuilder issues (class properties...)

$
0
0
I've also tried adding the following line inside the using statement
dbContext.Database.Initialize(true);
and also outside the using statement
_dbContext.Database.Initialize(true);
Same issue persists.

Updated Wiki: Home

$
0
0

Overview

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

Contribution & bug reports

Please use the Github project page.

Getting started

Updated Wiki: Documentation

Updated Wiki: Create a fake DbContext instance

$
0
0

In this tutorial we will create a fake DbContext instance.

Effort does not support the creation of DbContext directly, altering the behavior of a DbContext class requires the creation of fake DbConnection object. So the DbContext class should have the appropriate constructor:

publicclass MyDbContext : DbContext
{
    public MyDbContext(DbConnection connection) 
        : base(connection, true)
    {
    }
}

 

The DbConnectionFactory class provides helper methods to create fake DbConnection objects that can be used as the argument for the previously mentioned constructor.

DbConnection connection = Effort.DbConnectionFactory.CreateTransient();

MyDbContext context = new MyDbContext(connection);

 

Of course, the initial data can be set by using an appropriately created data loader.

IDataLoader loader = new Effort.DataLoaders.CsvDataLoader(csvFiles);

DbConnection connection = Effort.DbConnectionFactory.CreateTransient(loader);

MyDbContext context = new MyDbContext(connection);

 

Since the release of Visual Studio 2012 all kind of Entity Framework templates use DbContext by default, even if you want to use the Database First or Model First approach. In these cases if you used the previous technique, you would get an UnintentionalCodeFirstException.

If you experienced this issue you should use Effort in another way. Instead of DbConnectionFactory use the EntityConnectionFactory component and pass a connection string that refers to the EDMX file, just like if you used an ObjectContext.

EntityConnection connection =
    Effort.EntityConnectionFactory.CreateTransient("name=connectionString");

MyDbContext context = new MyDbContext(connection);
Viewing all 111 articles
Browse latest View live


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