Giter VIP home page Giter VIP logo

zzzprojects / entityframework-classic Goto Github PK

View Code? Open in Web Editor NEW
102.0 13.0 26.0 14.49 MB

Entity Framework Classic is a supported version of the latest EF6 codebase. It supports .NET Framework and .NET Core and overcomes some EF limitations by adding tons of must-haves built-in features.

Home Page: https://entityframework-classic.net

License: Other

C# 98.69% Smalltalk 0.10% Yacc 0.12% Lex 0.01% Batchfile 0.01% 1C Enterprise 0.58% PowerShell 0.01% Rich Text Format 0.23% TSQL 0.01% Visual Basic .NET 0.18% ASL 0.08%
entity-framework dotnet-framework orm database ef6 entity-framework-6 entity-framework-classic dotnet-core

entityframework-classic's Introduction

What's EF Classic?

Entity Framework Classic is a supported version from the latest EF6 codebase. It supports .NET Framework and .NET Core and overcomes some EF limitations by adding tons of must-haves built-in features.

Download: https://entityframework-classic.net/download

Who is it for?

If you are looking for performance enhancement, an Entity Framework version that's compatible with .NET Core, tons of new built-in features, and outstanding customer support. In that case, EF Classic is for you!

Why should you use it?

EF Classic is an EF6 fork compatible with .NET Core. It's a limitless version that includes tons of must-haves built-in features. Need support or a particular feature?

Features

Community (Free)

Enterprise

What will happen to your other prime & free libraries on Entity Framework?

Nothing will change. We will keep supporting them all.

  • Entity Framework Extensions: EF Classic has a dependency to this library.
  • Eval Expression.NET: EF Classic has a dependency to this library.
  • EF Effort: A version is available compatible with EF Classic
  • EF GraphDiff: We are currently investigating to either rewrite this library or to release a version compatible with EF Classic
  • Entity Framework Dynamic Filter: We will continue to support this library, but all features will be rewritten in EF Classic to add more flexibility.
  • Entity Framework Plus: We will continue to support this library, but all features will be rewritten in EF Classic to add more flexibility.

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-classic's People

Contributors

jonathanmagnan avatar lempireqc avatar mariloutb avatar slebleu avatar stgelaisalex avatar waqasm78 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

entityframework-classic's Issues

Identity with Z.EntityFramework.Classic

We are trying to combine Entity Framework Identity with Z.EntityFramework.Classic. When we install Identity packages from nuget, it also includes EF. Since Z.EntityFramework.Classic is the fork of orjinal EF the namespaces and classes are duplicated. Thus, it gives the following error on build.

Severity Code Description Project File Line Suppression State
Error CS0433 The type ‘DbSet’ exists in both ‘EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’ and ‘Z.EntityFramework.Classic, Version=7.0.0.0, Culture=neutral,

I have tried adding alias to differentiate the namespaces but didn't work out. How can we solve this? Is there any example about this?

ToList() returns no element

I'm implementing a Multi-Tenant application with Z.EntityFrameWork on .Net Framework. It looks to work great with Z.EntityFrameWork.Plus.EF6 and methods DbSetFilter and even QueryFilterManager.Filter but as it’s a new applications I tried to move to the Classic Community version (7.0.38) and it is not working.

My global filter looks like this :

this.Configuration.QueryFilter.Filter<Employee>(x => x.Tenants.Where(z => 
	z.DateFrom <= DateTime.Now 
	&& (z.DateTo == null || z.DateTo >= DateTime.Now) 
	&& z.ID_Tenant == userTenantId).Count() > 0);

I'm trying to do some global filtering and the .ToList() or .ToArray() methods returns no row. But the .Count() returns the right number of rows.

context.Employees.ToList()  not working, empty list is returned
context.Employees.Count()  Works!

Is this normal, could you help us on this point or do we have to forget this new Framework for the moment and keep the Plus EF6 version instead?

With the Sql Profiler I catched the query which returns the right rows. This makes me suppose that it's a bug in the Classic Community Framework.

Logging via Microsoft.Extensions.Logging?

Currently it would be great if EF-Classic would support logging via Microsoft.Extensions.Logging..
It took me a while to figure out that the query was really executed, since I had no visible logging, only my ef core logs would've been posted, so it first seemed that EF-Classic did not work.

actually for Z.EntityFramework.Plus.EFCore it should be relativ simple by using GetService<ILogger<Microsoft.EntityFrameworkCore.Database.Command>>
however would probably be problematic for ef5/ef6

Soft delete support

Some applications might not physically delete a data item. Instead, they usually add a flag to mark a data item deleted. Is it possible to support soft delete in BulkSynchronize and BulkDelete

Link to entityframework.net

I am converting a legacy app to .Net Core and I was just searching on how to call a Stored Procedure and I found the answer here.
But I noticed that you don't have a link to https://entityframework.net/ on your EF Classic website - So I would like to suggest this, it is a great documentation site and applies to EFC as well.

Also since Microsoft have moved on from EF6, I think you should primarily document your own product, perhaps consolidate your documentation into a sub-domain rather than pay for the extra domain?

EntityFrameworkManager.UseDatabaseFirst() assumes windows paths

When using a linux path when calling EntityFrameworkManager.UseDatabaseFirst() a DirectoryNotFoundException exception is thrown:

DirectoryNotFoundException: Could not find a part of the path '/app\bin/Debug/netcoreapp2.1/DataModel.edmx'.
  Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, string path, bool isDirectory, Func<ErrorInfo, ErrorInfo> errorRewriter)
  Microsoft.Win32.SafeHandles.SafeFileHandle.Open(string path, OpenFlags flags, int mode)
  System.IO.FileStream..ctor(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
  System.IO.StreamReader..ctor(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
  Z.EntityFramework.Classic.UseDatabaseFirstManager.Execute(string modelName)

Error when trying to using Cache for executing a store procedure

Hi Team,
I am trying to use Cache for a result from a store procedure like this

var employerInfo = _context.usp_get_cpr_employer_info(data.Identifier, data.PolicyId).AsQueryable().Cache().SingleOrDefault();

And I got an error below

System.Exception: Oops! The ObjectQuery cannot be found. Please use an explice key or report this issue here: https://github.com/zzzprojects/EntityFramework-Classic/issues
at Z.EntityFramework.Classic.QueryCacheManager.GetCacheKey(IQueryable query)

Could you please help to fix it

Thanks so much

Use Z.EntityFramework.Plus.EF6 with Classic

Hi,

we are using EntityFramework6 in our net4x Libraries and are evaluating migrating to netstandard.
Therefor we tried migrating some of the code to EntityFramework-Classic but failed at the point where we also use EntityFramework.Plus.EF6.

Is there a way to use those two libraries together or is there plans to integrate the features of "Plus" directly into "Classic". If so, is there any timeframe? One of the first missing methods we were looking at is DbContextExtensions.GetKeyNames.

Thanks,
Philipp

Make DbMigrator constructors public

Please make the following internal constructor of DbMigrator public - as it is in EF6:

    internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext)

DbMigrator - Problems with existing migrations

Hi!

We have migrated our application from EF 6.4.4 to EF Classic 7.1.34. We are using MS SQL Server as database. Usually the application user executes the pending migrations at application start. Internally the DbMigrator class is used for this in code:

var migrator = new DbMigrator(new Context.Configuration());
migrator.Update();

Since the migration to EF Classic we are facing problems with migrations of this type:

public override void Up()
{
	AddColumn("dbo.TableName", "ColumnName", c => c.Int(nullable: false));

	Sql("UPDATE dbo.TableName SET ColumnName = 123");
}

We are getting the exception that the column "ColumnName" is invalid at runtime, when the SQL-statement is executed. We can fix this problem with wrapping the SQL statement in an EXEC:

public override void Up()
{
	AddColumn("dbo.TableName", "ColumnName", c => c.Int(nullable: false));

	Sql("EXEC('UPDATE dbo.TableName SET ColumnName = 123')");
}

It seems that the DbMigrator is not finishing the batch after the AddColumn statement like EF 6.4.4 did. Is there any explanation for this or even a config option for getting the old behaviour?

Question

Hi,

I have the following case: my app has a known set of supported cultures, for each table/model, each varchar field, has a corresponding column for one of the known cultures, in the db - each column has a prefix for the culture e.g. book.title has a book.fr_title and book.ru_title. How can I use EF core to query the db in such way that it will get the data in to the model according to current culture ? In the model there is only one property book.title so the value should be mapped to this field. Is there a way to modify the EF Core generated SQL to select the correct column in the table according to the current culture - this is set in the db as a setting?

I would very much appreciate any kind of help.
(I want it to work like this, no extra additions: var books.Where(b=>b.price>23.2).ToList();)
I looked at computed properties but those did not work ..

Thanks.

Count() inside string expression in Execute method

I encounter on problem with Count() func inside the Query, while using Execute Extension method of yours.

_dataStoreService.GetAllElements().Execute<object>(
                "Where(p => (p.Name == \"test\"))" +
                ".Where(p => p.Active)" +
                ".Where(p => new List<int>() { 1, 2, 3 }.Contains(p.Id))" +
                ".GroupBy(p => new { p.Id, p.Name })" +
                ".Select(p => new { p.Key.Id, p.Key.Name, Counts =  p.Count() })" +
                ".ToList()")

Exception Details:

  • Message:
Processing of the LINQ expression '(GroupByShaperExpression:
KeySelector: new <>f__AnonymousType0<int, string>(
    Id = (s.Id), 
    Name= (s.Name)
), 
ElementSelector:new ElementDTO{ 
    Id = (ProjectionBindingExpression: Id), 
    Value = (ProjectionBindingExpression: Value), 
    Active = (ProjectionBindingExpression: Active), 
    Code = (ProjectionBindingExpression: Code), 
    Name = (ProjectionBindingExpression: Name) 
}
)' by 'RelationalProjectionBindingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.
  • Stack trace is:
at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node)
   at System.Linq.Expressions.UnaryExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitNew(NewExpression newExpression)
   at System.Linq.Expressions.NewExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Translate(SelectExpression selectExpression, Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Z.Expressions.EvalLinq.Execute(String code, Boolean isQueryable, Expression exp, Object[] parameters)
   at System.Linq.QueryableDynamic.Execute[TValue](IQueryable source, String expression, Object parameter)
   at System.Linq.QueryableDynamic.Execute[TValue](IQueryable source, String expression)
   at WebAPI.Controllers.ElementController.ZZZEntityFrameworkClassic(ZZZTransfer query) in *Path removed by me*\WebAPI\Controllers\ElementsController.cs:line 36
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeActionMethodAsync>g__Logged|12_1>d.MoveNext()

Cannot config correctly with runtime error: System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection cannot be cast, due to assemblies conflict between 'Z.EntityFramework.Classic' and 'EntityFramework.dll'.

Hi there,
I encountered this issue when a Unit test project using both EntityFramework and Z.EntityFramework.Classic.

nuget packages:

  <package id="MSTest.TestAdapter" version="1.2.0" targetFramework="net471" />
  <package id="MSTest.TestFramework" version="1.2.0" targetFramework="net471" />
  <package id="NMemory" version="2.0.4" targetFramework="net471" />
  <package id="Z.EntityFramework.Classic" version="7.0.17" targetFramework="net471" />
  <package id="Z.EntityFramework.Classic.Effort" version="1.3.10" targetFramework="net471" />
  <package id="Z.EntityFramework.Extensions.Classic" version="3.16.3" targetFramework="net471" />
  <package id="Z.Expressions.Eval" version="2.7.8" targetFramework="net471" /> 

app.config:

<configuration>
  <configSections>    
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, Z.EntityFramework.Classic, Version=7.0.0.0, Culture=neutral, PublicKeyToken=afc61983f100d280" requirePermission="false" />   
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,  Z.EntityFramework.Classic">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, Z.EntityFramework.Classic.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

have used ChangeAliases in *.csproj to resolve build errors:

    <ItemGroup>
      <ReferencePath Condition="'%(FileName)' == 'Z.EntityFramework.Classic'">
        <Aliases>signed</Aliases>
      </ReferencePath>
    </ItemGroup>
  </Target>

exception throw when initial a context during run time:

System.TypeInitializationException: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. 
---> System.InvalidCastException: [A]System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection cannot be cast to [B]System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection. 
Type A originates from 'Z.EntityFramework.Classic, Version=7.0.0.0, Culture=neutral, PublicKeyToken=afc61983f100d280' in the context 'Default' at location '@ProjectPath\bin\Debug\Z.EntityFramework.Classic.dll'. 
Type B originates from 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'Default' at location '@ProjectPath\bin\Debug\EntityFramework.dll'.
    at System.Data.Entity.Internal.AppConfig..ctor()
   at System.Data.Entity.Internal.AppConfig..cctor()
--- End of inner exception stack trace ---
    at System.Data.Entity.Internal.AppConfig.get_DefaultInstance()
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForAssembly(Assembly assemblyHint, Type contextTypeHint)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForContext(Type contextType)
   at System.Data.Entity.DbContext.InitializeLazyInternalContext(IInternalConnection internalConnection, DbCompiledModel model)
   at System.Data.Entity.DbContext..ctor(DbConnection existingConnection, Boolean contextOwnsConnection)

so any clue of this?
Cheers~

Current Values are not reset when using SoftDelete

Hello,

I have an entity Folder with SubFolders.
I am using a SoftDelete trigger, which works as expected.
Except, the ParentFolderId is reset to NULL when a Child folder is deleted.
This happens I think because I use DbSet.Remove(folder), and as a result it will remove the child folder from the parent entities Folder collection.
The result of this is that the property ParentFolderId of the folder I want to delete is set to NULL.
This change is also persisted to the database.

The workaround which I use now is to reset the CurrentValues.
This does not feel like the correct way. Should this be something what EF Classic should be doing or does anyone have tips how te prevent this problem.

image

image

Could not find the context from IQueryable expression

EF Classic throws for me could not find context and I am not sure why.

This throws Could not find the context from the IQueryable expression. Are you sure this is coming from an Entity Framework Context?

await _db.Items
    .Where(o => o.HierarchyId == fromHierarchyId)
    .UpdateFromQueryAsync(
        o => new Item {HierarchyId = toHierarchyId}
    );
await _db.SaveChangesAsync();

But this works fine

var list = await _db.Objects
    .Where(o => o.HierarchyId == fromHierarchyId)
    .ToListAsync();
list.ForEach(o => {
  o.HierarchyId = toHierarchyId;
});
await _db.SaveChangesAsync();

What am I missing?

I am using Z.EntityFramework.Classic 7.1.17
EF Core 2.2.6
.NET Core 2.2

"Cannot bind argument to parameter 'Path' because it is an empty string" when running Add-Migration

When I run “Add-Migration” from the package manager console, I get:

PM> Add-Migration test
Join-Path : Cannot bind argument to parameter 'Path' because it is an empty string.
At D:\Projekte\Azure\CMT\Source\Packages\z.entityframework.classic\7.1.25\tools\EntityFramework.psm1:715 char:28
+     $toolsPath = Join-Path $installPath tools
+                            ~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand

Join-Path : Cannot bind argument to parameter 'Path' because it is null.
At D:\Projekte\Azure\CMT\Source\Packages\z.entityframework.classic\7.1.25\tools\EntityFramework.psm1:782 char:74
+ ...  [System.Reflection.Assembly]::LoadFrom((Join-Path $ToolsPath EntityF ...
+                                                        ~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand

You cannot call a method on a null-valued expression.
At D:\Projekte\Azure\CMT\Source\Packages\z.entityframework.classic\7.1.25\tools\EntityFramework.psm1:783 char:5
+     $dispatcher = $utilityAssembly.CreateInstance(
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Join-Path : Cannot bind argument to parameter 'Path' because it is null.
At D:\Projekte\Azure\CMT\Source\Packages\z.entityframework.classic\7.1.25\tools\EntityFramework.psm1:812 char:20
+         (Join-Path $runner.ToolsPath EntityFramework.PowerShell.dll),
+                    ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand

PM>

Please note that in my project, I have moved the DbContext and the Migrations into a separate assembly “CMT.DataAccess” and the Model into an assembly “CMT.DataAccess.Model”. This worked fine for EF6. To migrate from EF6 to EFClassic, I removed all EntityFramework packages and installed the EFClassic packages as described in the documentation.

Saving with a DB error results in Secure binary serialization is not supported on this platform

I'm doing a SaveChanges on an object which contains an error (invalid reference to a FK object), but instead of throwing the actual error it throws:

System.PlatformNotSupportedException: 'Secure binary serialization is not supported on this platform.

If I change my SaveChanges in await SaveChangesAsync it swallows the error and hangs forever.

This is on the latest version with a .NET Core 2.1 project.

Stacktrace:

at System.Exception.add_SerializeObjectState(EventHandler`1 value)
at System.Data.Entity.Internal.InternalContext.WrapUpdateException(UpdateException updateException)
at System.Data.Entity.Internal.InternalContext.SaveChanges()

DbGeography support

I noticed that DbGeography is included in the library but when I run it I get:

Spatial types and functions are not available for this provider because the assembly 'Microsoft.SqlServer.Types' version 10 or higher could not be found

How would one go about installing/including Microsoft.SqlServer.Types in a .NET core project?

Problem mocking DbSet and using Include

I have this line of code inside a method:

var orders = dbContext.Customers.Include(s => s.Orders).ToList();

I'm trying to create unit tests for that method, but I get the following exception:

The member 'IEnumerable<TResult>.GetEnumerator' has not been implemented on type 'IncludeDbQuery`2' which inherits from 'DbSet`1'. Test doubles for 'DbSet`1' must provide implementations of methods and properties that are used.

I've tried providing an implementation of the DbSet for the tests:

var data = new List<CustomerEntity>
{
    new CustomerEntity
    {
        CustomerId = "CustomerId",
        Orders = new[]
        {
            new OrderEntity
            {
                CustomerId = "CustomerId",
                OrderName = "OrderName"
            }
        }
    }
}.AsQueryable();

var mockSet = new Mock<DbSet<CustomerEntity>>();
mockSet.As<IQueryable<CustomerEntity>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<CustomerEntity>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<CustomerEntity>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<CustomerEntity>>().Setup(m => m.GetEnumerator()).Returns(() => data.GetEnumerator());

mockDbContext.Setup(c => c.Customers).Returns(mockSet.Object);

But now, I'm getting an Object reference not set to an instance of an object error.

What am I missing?

This solution is working using EntityFramework 6, but not with EF Classic. I know that Include now returns an IncludeDbQuery instead of an IQueryable , but I still don't know what mock I am missing.

How to share query plan accross query DbContext instances ?

While profiling our asp.net application we discovered that a new execution plan seems to created every time the request is executed.
The test sends 20 requests to the server which triggers the same request to the database. Each database request is executed on new DbContext instance.

Is there an option to cache the execution plan across instances of Db ?

This screenshot shows the cumulative time spent by multiple requests creating the execution plan.
image

Exception: 'Stream not found.' when using UpdateFromQueryAsync

Here's the stacktrace:

   at .(DbContext this, String )
   at .(DbContext this, List`1 , String )
   at .(DbContext )
   at .(DbContext )
   at .(DbContext this)
   at DbContextExtensions.UpdateFromQuery[TEntity](IQueryable`1 query, Expression`1 updateExpression, Action`1 bulkOperationFactory)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
   at DbContextExtensions.UpdateFromQueryAsync[TEntity](IQueryable`1 query, Expression`1 updateExpression)

It's hard to tell exactly what's going on, but at a guess it looks like something is trying to read the csdl, ssdl and msl, but not loading it from the in memory resources generated by EntityFrameworkManager.UseDatabaseFirst()

Sorry if this isn't the correct repo for this issue, I wasn't sure where to log issues for Z.EntityFramework.Extensions.Classic

Version:

  • Z.EntityFramework.Classic 7.0.12
  • Z.EntityFramework.Extensions.Classic 3.15.19

OS: Windows 10
TargetFramework: netcoreapp2.1

Migration examples

As per your docs:

Unfortunately, migrations tool for .NET Core is not yet supported by our library. However, you can create a side project in .NET Framework to generate the migrations.

Should anyone please guide me to a link or example explaining how we can achieve this?

Thanks.

IDbContext

Hello,

I think an IDbContext would be a good thing.
I pass my context's around using DI, so I always have an interface for each each context, but these interfaces only have the DbSet properties on them, and my repository isn't aware of SubmitChanges etc.
An interface that contains all common DbContext methods would be useful.

Thanks,

Luke

Is it possible to use DynamicFilters together with EntityFramework-Classic?

We are migrating our projects to .Net Standard. We were using EF 6 and EntityFramework.DynamicFilters.

For the migration, we replaced EF with the Z.EntityFramework.Classic (version 7.0.22) package. But we had to remove the EntityFramework.DynamicFilters package because it uses EF and we get errors using it together with Z.EntityFramework.Classic.

Is there any way to define filters in DbContext.OnModelCreating? Will the EntityFramework.DynamicFilters package be compatible with EntityFramework-Classic?

HierarchyId.GetAncestor method raise an unexpected exception

Hello,
I am using version 7.1.43 of the library.
This code produces an exception:

    [TestMethod]
    public void HidGetAncestorTest() {
        HierarchyId hid = HierarchyId.GetRoot().GetDescendant(null, null);
        HierarchyId parent = hid.GetAncestor(1);
        Assert.AreEqual(HierarchyId.GetRoot().ToString(), parent.ToString());
    }

Error:

Test method UnitTests.DynamicCollectionTests.HidGetAncestorTest threw exception: 
System.ArgumentException: The input string '//' is not a valid string representation of a HierarchyId node.
Parameter name: hierarchyId
    в System.Data.Entity.Hierarchy.HierarchyId..ctor(String hierarchyId)
   в System.Data.Entity.Hierarchy.HierarchyId.GetAncestor(Int32 n)

The reason is a wrong implementation of GetAncestor method in this library version:

    /// <summary>
    ///     Returns a hierarchyid representing the nth ancestor of this.
    /// </summary>
    /// <returns>A hierarchyid representing the nth ancestor of this.</returns>
    /// <param name="n">n</param>
    public HierarchyId GetAncestor(int n) => this._nodes == null || (int) this.GetLevel() < n ? new HierarchyId((string) null) : new HierarchyId("/" + string.Join("/", ((IEnumerable<int[]>) this._nodes).Take<int[]>((int) this.GetLevel() - n).Select<int[], string>(new Func<int[], string>(HierarchyId.IntArrayToStirng))) + "/");

EntityFramework 6.4.0 has this fixed:

    /// <summary>
    ///     Returns a hierarchyid representing the nth ancestor of this.
    /// </summary>
    /// <returns>A hierarchyid representing the nth ancestor of this.</returns>
    /// <param name="n">n</param>
    public HierarchyId GetAncestor(int n)
    {
      if (this._nodes == null || (int) this.GetLevel() < n)
        return new HierarchyId((string) null);
      return (int) this.GetLevel() == n ? new HierarchyId("/") : new HierarchyId("/" + string.Join("/", ((IEnumerable<int[]>) this._nodes).Take<int[]>((int) this.GetLevel() - n).Select<int[], string>(new Func<int[], string>(HierarchyId.IntArrayToStirng))) + "/");
    }

this is the fix:

(int) this.GetLevel() == n ? new HierarchyId("/") : 

Merging EF 6.4 to Classic is desired to fix this, but may take significant time.
Could you please make a hotfix in the library?

It would be very helpful.

Thanks,
Roman

Jetbrains Rider EF 6.2 commands

I use Jetbrains Rider for all my C# development. They have contextmenu based EF 6.2 migration support. As EF version is detected based on referenced EF dll (I think so, no extra information provided by Jetbrains) then for Classic I don't have EF context menu.

It is more like Rider issue, but I'm not switching to Visual Studio so until EF 6.3 Classic isn't usable for me. I still can use Extensions so not big problem, but would like to use Classic.

I created Rider issue and they can add support for Classic. Maybe I'm here the middleman and you should directly communicate with them? https://youtrack.jetbrains.com/issue/RIDER-28099

this.Configuration not availalbe in .net core 6 for soft delete

I using your trial version of EF classic for soft delete, here i can't find this.Configuration.

image

don't know who's this issue from whose side?

===
Also plz let us know what we can do if we use database first approch, because all the time it removed when we scaffold from database first

MySql Provider Implementation

First of all, thank you for creating such an important project for those who are frustrated with some of the quirks of EF Core. For my project, we use MariaDb in production. Is there an ETA for when you'll implement provider support for MySQL? Thanks! 👍

Enum model property support?

According to Microsoft, I should be able to use automatically-mapped enum types in my model definitions: https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-types/enums

When using EntityFramework-Classic, the model compiles correctly, but when I attempt to load the context, I get errors similar to:

ArgumentException: The ResultType of the specified expression is not compatible with the required type. The expression ResultType is 'MyEnumType' but the required type is 'Edm.Int32'.
Parameter name: keyValues[0]

System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.RequireCompatibleType(DbExpression expression, TypeUsage requiredResultType, string argumentName, int argumentIndex)
EntityCommandCompilationException: An error occurred while preparing the command definition. See the inner exception for details.

System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory)

Am I missing something in the configuration of my DbContext? This is all I have in OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
 }

I also added this to the property in question, which doesn't seem to help:

[Column("TypeID", TypeName ="int")]
public MyEnumType TypeID { get; set; }

My TypeID column is a foreign key, if it's relevant.

How does the licensing work?

This library seems to have a community (free) version, but it depends on the Z.Expressions.Eval package, which does not have a free version, so how does the licensing work?

Type not supported yet (LazyType): sdo_geometry

Call the "DeleteFromQuery", the database contains the spatial data type will throw the error: Type not supported yet (LazyType): sdo_geometry.

Database: Oracle 11g.
.Net Framework 4.7
EntityFramework 6.4.
Provider: Devart.Data.Oracle

I just want to use the "DeleteFromQuery" for the entity and the entity doesn't have the geometry column, and the other data table contains.
Since the entity which just wants to delete doesn't contain the geometry column, why throw the error message? It blocks me.

Anyone can give some suggestions? Thanks so much.

Cte support

Hi there just wondering if there's any plans to support ctes (common table expressions)

HierarchyId support

Hello,
We have a license for EF Classic, but cannot migrate our code to it because of absent HierarchyId support.
It would be very helpful if HierachyId will be introduced. We used EF beta nightly build and everything is OK. More details here: dotnet/ef6@f905073.
Thanks, Roman

Cache extension method does multiple initialization in parallel access

Hello,

I have detected that Cache extention method does not implement thread-safe initialization.
In our app we are using WEB API and each route uses the same logic for validating access. This logic makes a query to DB to get large set of data. Cache extension helps us improve performance by avoiding this expensive query while data is not changed.

However, if query result is not in cache yet, then multiple requests may occur to DB for the same query.

In our case we are making 3 parallel calls to different WEB API routes( all of them uses the same query to get data for validation). In result in SQL Profiler we see 3 SQL queries instead of 1.
This occurs because processing of the query takes long time, 1-3 sec, and multiple requests to cache from different threads try to initialize the cache.

I have found a good article that describes the same issue in more details and provides interesting fix:
Working with System.Runtime.Caching.MemoryCache

What do you think about this?

From my point of view it would be good to have ability to avoid multiple cache initialization using the way suggested in the article.
It may be good to have separate implementation of Cache extension method from existing one or just add a parameter to existing, that switch internal behavior. Just to minimize side effects for existing applications.

Thanks,
Roman

Extend description what EF Classic does.

The readme and http://entityframework-classic.net/ doesn’t clarify what EF Classic does and how it relates with your other projects, such as Entity Framework Extensions, Entity Framework Plus, Entity Framework Dynamic Filters, GraphDiff and Effort.

Also does “Built for developers by Entity Framework developers” means that you have Microsoft employees, who wrote/are writing Microsoft Entity Framework? If not, please rephrase the statement to avoid ambiguity.

Creating new array inside expression string - Execute extension method

With this expressions string passed into Execute extension method:

Where(p => new []{ 1, 2, 3, 4 }.Contains(p.Id))

library loses the new keyword and replace it with (IEnumerable<int>) cast, so causing exception.

Example repo (newArray branch) replicating the problem.

Exception details:

  • Message:
The LINQ expression 'DbSet<Element>
    .Where(e => e.Name == "test")
    .Where(e => e.Active)
    .Where(e => (IEnumerable<int>)int[] { 1, 2, 3, 4, }
        .Contains(e.Id))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
  • Stack trace:
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.<VisitMethodCall>g__CheckTranslated|8_0(ShapedQueryExpression translated, <>c__DisplayClass8_0& )
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Z.Expressions.EvalLinq.Execute(String code, Boolean isQueryable, Expression exp, Object[] parameters)
   at System.Linq.QueryableDynamic.Execute[TValue](IQueryable source, String expression, Object parameter)
   at System.Linq.QueryableDynamic.Execute[TValue](IQueryable source, String expression)
   at EntityFramework_Classic_Count_example.Program.Main(String[] args) in *Removed by me*\EntityFramework-Classic_Count_example\EntityFramework-Classic_Count_example\Program.cs:line 21

Include with InvalidCastException exception

The following code leads to an InvalidCastException exception:

public ICollection<Entity> QueryBy(long tenantID)
{
         return this.DbContext.Entities
                  .Where(x => x.TenantID == tenantID)
                  .Include(x => x.OtherEntity)
                  .ToList();
}

Exception details:

'Das Objekt des Typs "System.Data.Entity.Core.Objects.ObjectQuery`1[CMT.DataAccess.Model.Entity]" kann nicht in Typ "System.Data.Entity.Infrastructure.DbQuery`1[CMT.DataAccess.Model.Entity]" umgewandelt werden.'

Port EF 6.3 migration generator

Is there any chance for you guys to port the migration generator from EF 6.3 to EF Classic to support .NET Core 2?

Alternatively, could you possibly release Z.EntityFramework.Classic.MySql retargeted for EF 6.3? Oracle hasn't made any effort to release their provider for .NET Standard/Core, so even if we wanted to update to EF 6.3, we have no MySQL provider to use.

Effort with DbFirst model on .Net Framework 4.0 or newer seems unusable or not documented

Hi. Sory for bad english and maybe for issue on wrong project.

I've trying to use Z.EntityFramwrodk.Classic.Effort in test project with an DbFirst model and <TargetFramework>net462</TargetFramework>, but can't get any luck with it.
Once DbContext created - it goes with CodeFirst way and throws standard UnintentionalCodeFirstException.

I've tried it as in documentation example, like:

var connection = Effort.DbConnectionFactory.CreateTransient();
var context = new EntityContext(connection));

But, at least in documentation, there is no any way to specify some *.edmx model.
It seems to me - there need to call EntityFrameworkManager.UseDatabaseFirst("SomeModel.edmx") like in .netstandard2.0 target, but this method is missed in net45 target library of Z.EntityFramework.Classic

EDMX - Unable to cast object of type ObjectQuery to DbQuery in .Include()

Many thanks for your work on the amazing Z.EntityFramework.Plus and Z.EntityFramework.Classic.

Currently I'm using EDMX and EntityFramework 6.4.4 with Z.EntityFramework.Plus.EF6 and everything works great.

Currently I have to migrate my project to new .NET 7 and I have to do this incrementally. In first step I want to compile my project to .NET Standard 2.0, so I need to use Z.EntityFramework.Classic. I changed the nugets, my project compiles fine, but I got exception at runtime.

System.InvalidCastException: Unable to cast object of type 'System.Data.Entity.Core.Objects.ObjectQuery`1[DatabaseAPI.User]' to type 'System.Data.Entity.Infrastructure.DbQuery`1[DatabaseAPI.User]'.
   at EntityFrameworkClassicExtensions.AsDbQuery[TQuery](IQueryable`1 this)
   at System.Data.Entity.QueryableExtensions.Include[TResult,TProperty](IQueryable`1 source, Expression`1 path)
   at CommandCenter.Repositories.UsersRepository.GetQueryable() in C:\code\CommandCenter\CommandCenterInfrastructure\CommandCenter.Repositories\UsersRepository.cs:line 83
   at CommandCenter.Repositories.GenericRepository`2.Get(Expression`1 predicate) in C:\code\CommandCenter\CommandCenterInfrastructure\CommandCenter.Repositories\GenericRepository.cs:line 91
   at CommandCenter.Services.UsersProvider.Get(String login, Boolean ignoreCase) in C:\code\CommandCenter\CommandCenterDomain\CommandCenter.Services\UsersProvider.cs:line 93
   at WebAPI.Filters.Validators.Utils.HttpRequestSignatureValidator.Validate(HttpRequestMessage request) in C:\code\CommandCenter\WebAPI\Filters\Validators\Utils\HttpRequestSignatureValidator.cs:line 99
   at WebAPI.Filters.Validators.ApiUserAuthorizeAttribute.DoesValidRequestSignatureExist(HttpActionContext context) in C:\code\CommandCenter\WebAPI\Filters\Validators\ApiUserAuthorizeAttribute.cs:line 109
   at WebAPI.Filters.Validators.ApiUserAuthorizeAttribute.CustomOnAuthorization(HttpActionContext context) in C:\code\CommandCenter\WebAPI\Filters\Validators\ApiUserAuthorizeAttribute.cs:line 84
   at WebAPI.Filters.Validators.CustomAuthorizeAttribute.OnAuthorization(HttpActionContext context) in C:\code\CommandCenter\WebAPI\Filters\Validators\CustomAuthorizeAttribute.cs:line 58
   at System.Web.Http.Filters.AuthorizationFilterAttribute.OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()

I'm using EDMX that generates my MyEntities context:

public partial class MyEntities : ObjectContext
{
        public ObjectSet<User> Users
        {
            get
            {
                if ((_Users == null))
                {
                    _Users = base.CreateObjectSet<User>("Users");
                }
                return _Users;
            }
        }
        private ObjectSet<User> _Users;

/// Other collections ...
}

Then I get data with Include() method:

public override IQueryable<User> GetQueryable()
{
    return this.Entities.Users.AsQueryable()
        .Include(i => i.UserPrivileges)
        .Include(i => i.UserEmails)
        .Include(i => i.UserSetting);
}

I've used DotPeek because I wanted to understand this problem and I saw the following implementation:

  public static class QueryableExtensions
  {
....
    public static IIncludeDbQuery<TResult, TProperty> Include<TResult, TProperty>(
      this IQueryable<TResult> source,
      Expression<System.Func<TResult, TProperty>> path)
    {
      Check.NotNull<Expression<System.Func<TResult, TProperty>>>(path, nameof (path));
      string path1;
      if (!DbHelpers.TryParsePath(path.Body, out path1) || path1 == null)
        throw new ArgumentException(System.Data.Entity.Resources.Strings.DbExtensions_InvalidIncludePathExpression, nameof (path));
      return (IIncludeDbQuery<TResult, TProperty>) new IncludeDbQuery<TResult, TProperty>(source.Include<TResult>(path1).AsDbQuery<TResult>(), path1);
    }
...

The Include() method returns even different type. It should returns IQuerable<T> but it returns IIncludeDbQuery<TResult, TProperty> and that requires a lot of code changes after changing the library.

Then I've checked the code on master, and it looks different:

public static IQueryable<T> Include<T, TProperty>(
this IQueryable<T> source, Expression<Func<T, TProperty>> path)
{
Check.NotNull(source, "source");
Check.NotNull(path, "path");
string include;
if (!DbHelpers.TryParsePath(path.Body, out include)
|| include == null)
{
throw new ArgumentException(Strings.DbExtensions_InvalidIncludePathExpression, "path");
}
return Include(source, include);
}

I don't know why but it takes code from:

public IIncludeDbQuery<TQuery, TProperty> Include<TProperty>(Expression<Func<TPropertyCurrent, TProperty>> path)
{
string include;
if (!DbHelpers.TryParsePath(path.Body, out include) || include == null)
{
throw new ArgumentException(Strings.DbExtensions_InvalidIncludePathExpression, "path");
}
return new IncludeDbQuery<TQuery, TProperty>(Include(include), include);
}

I've checked the latest version of library 7.2.5 and 7.2.4

The same exception was created #53 but user close this issue because he move back to EF + EF.Plus.

HasNoKey and Constructor with Parameters

Hello,

I am converting a project from Entity Framework Core to Entity Framework Classic due to some limitations of things that I used to be able to do in EF6 but no longer can... It seems there are also some things you can do in Core that you cannot do in ES6

The first one is that I have views in my database, these views are made from joining a number of tables together, the views have no primary key and with Core we can do .HasNoKey() in the DB context.
Any chance of you adding this to your framework?

The other thing is not so important, I can get around it by Select().AsEnumerable(), but it would be nice.
I am getting ye olde Only parameterless constructors and initializers are supported in LINQ to Entities because I have a class like this:
(I guess I could refactor)

public class NameValue<T>
{
  public string Name { get; set; }
  public T Value { get; set; }
  public NameValue(string name, T value)
  {
    Name = name;
    Value = value;
  }
}

What do you think?
The HasNoKey issue will mean that I am stuck untill I figure out the unique composite key combination.

InvalidOperationException when using .Future() within a transaction

When attempting to use .Future() and QueryFutureEnumerable.ToListAsync() within a transaction I get the following exception:

InvalidOperationException: BeginExecuteReader requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.
  System.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__122_0(Task<SqlDataReader> result)
  System.Threading.Tasks.ContinuationResultTaskFromResultTask<TAntecedentResult, TResult>.InnerInvoke()
  System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, object state)
  System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref Task currentTaskSlot)
  .(CancellationToken cancellationToken)
  Z.EntityFramework.Classic.QueryFutureBatch.ExecuteQueriesAsync(CancellationToken cancellationToken)
  Z.EntityFramework.Classic.QueryFutureEnumerable<T>.ToListAsync(CancellationToken cancellationToken)
  ...

Version: Z.EntityFramework.Classic 7.0.12
OS: Windows 10
TargetFramework: netcoreapp2.1

Error when using UpdateFromQuery on an expanded query (Linqkit)

Hi,

we have noticed that the UpdateFromQuery()/DeleteFromQuery() methods does not work with an expanded query.
I've created a small runnable example where this problem can be reproduced.

private static Expression<Func<Customer, bool>> _testFilterExpression = c => c.Name == "abc";

public static void Main(string[] args)
{

	try
	{
		var ctx = new TestContext();
		var simpleRequest = ctx.Customers.Count();
		
		// this works
		var batchUpdate = ctx.Customers
			.Where(c => c.Name == "abc")
			.UpdateFromQuery(c => new Customer { Name = "Test" });
		
		// this crushes
		var batchLinqKitUpdate = ctx.Customers
			.AsExpandable()
			.Where(c => _testFilterExpression.Invoke(c) && c.Id > 0)
			.UpdateFromQuery(c => new Customer { Name = "Test" });
	}
	catch (Exception e)
	{
		
	}
}

System.Exception: Could not find the context from the IQueryable expression. Are you sure this is coming from an Entity Framework Context?
at .[](IQueryable1 ) at DbContextExtensions.[](IQueryable1 , Expression1 , Action1 , Boolean )
at DbContextExtensions.Update
efClassicAndLinqKit.zip
FromQuery[TEntity](IQueryable1 query, Expression1 updateExpression, Action1 bulkOperationFactory) at DbContextExtensions.UpdateFromQuery[TEntity](IQueryable1 query, Expression`1 updateExpression)
at ConsoleApp.Program.Main(String[] args) in C:\dev\test_projects\efClassicAndLinqKit\ConsoleApp\Program.cs:line 28

Maybe you can give me a hint, what is wrong here?

I'm using
Z.EntityFramework.Classic 7.1.34
LinqKit.Z.EntityFramework.Classic 1.1.17
efClassicAndLinqKit.zip

Exception: NullReferenceException when using .Where(x => x.Field.Contains(txt))

The following query throws a NullReferenceException:
Context.Games.Where(x => x.Name.Contains(searchText)).ToListAsync();

The problems seems to be the string.Contains() method.

EntityFramework-Classic version: 7.0.24

Here is the stack trace:

System.NullReferenceException: Object reference not set to an instance of an object.
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitMethodCall(Expression obj, MethodInfo method, IArgumentProvider methodCallExpr, CompilationFlags flags)
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitInvocationExpression(Expression expr, CompilationFlags flags)
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitExpression(Expression node, CompilationFlags flags)
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitInstance(Expression instance, Type& type)
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitMemberExpression(Expression expr)
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitExpression(Expression node, CompilationFlags flags)
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitLambdaBody(CompilerScope parent, Boolean inlined, CompilationFlags flags)
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitLambdaBody()
at System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression lambda)
at System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.EvaluateParameter(Object[] arguments)
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass43_0.b__1()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransactionAsync[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess, CancellationToken cancellationToken) at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.ExecuteAsyncImplementation[TResult](Func1 func)
at System.Data.Entity.Core.Objects.ObjectQuery1.GetResultsAsync(Nullable1 forMergeOption, IDbExecutionStrategy executionStrategy, CancellationToken cancellationToken)
at System.Data.Entity.Internal.LazyAsyncEnumerator1.FirstMoveNextAsync(CancellationToken cancellationToken) at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.SingleAsync[TSource](IDbAsyncEnumerable1 source, CancellationToken cancellationToken)

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.