Quantcast
Channel: Entity Framework
Viewing all 10318 articles
Browse latest View live

Commented Unassigned: CloneDbCommand throws Exception in 6.1.2-beta1 [2554]

$
0
0
Dear Sirs,

the CloneDBCommand throws an Exception if one uses EF together with StackExchange MiniProfiler:

```
Any exception caught System.InvalidCastException: Das Objekt des Typs "StackExchange.Profiling.Data.ProfiledDbCommand" kann nicht in Typ "System.Data.SqlClient.SqlCommand" umgewandelt werden.
bei System.Data.Entity.SqlServer.SqlProviderServices.CloneDbCommand(DbCommand fromDbCommand)
bei System.Data.Entity.Core.Common.DbCommandDefinition.CreateCommand()
bei EFCache.CachingCommandDefinition.CreateCommand()
bei System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.PrepareEntityCommandBeforeExecution(EntityCommand entityCommand)
bei System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
bei System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
bei System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
bei System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
bei System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
bei System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
bei System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__0[TResult](IEnumerable`1 sequence)
bei System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
bei System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
bei System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
bei System.Linq.Queryable.First[TSource](IQueryable`1 source)
```

There was no problem in EF 6.1.1.

With best regards

Rufus
Comments: Thank you!

Created Unassigned: InvalidCastException When Attaching Entity in EF 5 with Different Types to Those Being Attached [2567]

$
0
0
SO Post
http://stackoverflow.com/questions/26511136/invalidcastexception-when-calling-attach-entity-framework-5

Using TPT

Basically I have a Type that has a table (GeneralBasketItem). This is mapped to another type that is a sub class table (PromAppliedPromDisc). I have tried mapping to the abstract class table that this derives from as well.

When attaching an instance of GeneralbasketItem I get an invalidcastexception that talks about trying to cast a PromAppliedPromDisc to another, third type to which PromAppliedPromDisc is related.

This error is very inconsistent.

Error Message:
System.InvalidCastException was unhandled by user code
HResult=-2147467262
Message=Unable to cast object of type 'System.Data.Entity.DynamicProxies.PromAppliedPromDisc_1C9679CDF0894595D5C7F947F690F6BF3089E89365FF83ECCF370C91C37616ED' to type 'CoreTillDAL.PromBaskItemDisc'.
Source=System.Data.Entity
StackTrace:
at System.Data.Objects.DataClasses.EntityReference`1.AddToLocalCache(IEntityWrapper wrappedEntity, Boolean applyConstraints)
at System.Data.Objects.EntityEntry.TakeSnapshotOfSingleRelationship(RelatedEnd relatedEnd, NavigationProperty n, Object o)
at System.Data.Objects.EntityEntry.TakeSnapshotOfRelationships()
at System.Data.Objects.Internal.EntityWrapperWithoutRelationships`1.TakeSnapshotOfRelationships(EntityEntry entry)
at System.Data.Objects.ObjectContext.AttachSingleObject(IEntityWrapper wrappedEntity, EntitySet entitySet, String argumentName)
at System.Data.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.EntityReference`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach)
at System.Data.Objects.ObjectContext.AttachTo(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClass2.<Attach>b__1()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Attach(Object entity)
at System.Data.Entity.DbSet`1.Attach(TEntity entity)
at CoreTillDAL.PromDiscPointsPerItem.AdjustBaskItems(HashSet`1 UsedDiscItems) in C:\Users\neil.clarke\Documents\Visual Studio 2012\Projects\Plugins\DBPromPlugin1\Plugins Classes\PromAndDisc\PromDiscPointsPerItemE.vb:line 29
at CoreTillDAL.GeneralBasket.AdjustBIsforProms() in C:\Users\neil.clarke\Documents\Visual Studio 2012\Projects\Plugins\DBPromPlugin1\Core Classes\EF Ext Classes\Till\GeneralBasketE.vb:line 254
at CoreTillDAL.GeneralBasket.ApplyBIandBaskDiscounts() in C:\Users\neil.clarke\Documents\Visual Studio 2012\Projects\Plugins\DBPromPlugin1\Core Classes\EF Ext Classes\Till\GeneralBasketE.vb:line 173
at CoreTillDAL.PotAppliedProm.SavePromotionToBasketorItems(Int64 PromIDForThisVal, Boolean ManualActivation, Int64 BasketID, Dictionary`2 UsedBuyItems, Boolean test) in C:\Users\neil.clarke\Documents\Visual Studio 2012\Projects\Plugins\DBPromPlugin1\Plugins Classes\PromClasses\PotentialProms\PotAppliedProm.vb:line 172
at PromPlugin.DPromAutoApplicator.ApplyBestPromotiontoItems() in C:\Users\neil.clarke\Documents\Visual Studio 2012\Projects\Plugins\PromDomainPlugin\AutoPromotions\DPromAutoApplicator.vb:line 92
at PromPlugin.DPromAutoApplicator.CalcandApplyPromsToBasket(GeneralBasketItem NewBasketItem) in C:\Users\neil.clarke\Documents\Visual Studio 2012\Projects\Plugins\PromDomainPlugin\AutoPromotions\DPromAutoApplicator.vb:line 59
at PromPlugin.DPromController.HandleBaskItemAdded(Object o, BaskItemAddedEventArgs e) in C:\Users\neil.clarke\Documents\Visual Studio 2012\Projects\Plugins\PromDomainPlugin\AutoPromotions\DPromController.vb:line 53
at CoreTillDAL.CoreTill.FakeAddBasketItem(Int64 BasketID, Int64 ProductID) in C:\Users\neil.clarke\Documents\Visual Studio 2012\Projects\Plugins\DBPromPlugin1\Core Classes\EF Ext Classes\Till\CoreTill.vb:line 50
at UnitTests.TestingStoredProcs.DeleteAppliedPromsandFakeAddBI(CoreTill Ctill, Int64 BasketID, Int64 ProdID) in C:\Users\neil.clarke\Documents\Visual Studio 2012\Projects\Plugins\UnitTests\TestingStoredProcs.vb:line 967
at UnitTests.TestingStoredProcs.addBasketItemsToTriggerProm(GeneralBasket Basket, Int64 PromID, DPromController& PromCont) in C:\Users\neil.clarke\Documents\Visual Studio 2012\Projects\Plugins\UnitTests\TestingStoredProcs.vb:line 555
at UnitTests.TestBasicTests.TestAllBasicPromsAuto() in C:\Users\neil.clarke\Documents\Visual Studio 2012\Projects\Plugins\UnitTests\TestClasses\TestBasicTests.vb:line 264
InnerException:



Commented Issue: Query: Cast introduced for enum properties may prevent SQL from using indexes [186]

$
0
0
"In this it might have to do with the fact that it is using function mapping (it is a TVF), but I am not sure.

var products = from p in db.ProductsByName(""%ich%"")
where p.Category == Categories.Food
select p;

I think this kind of cast tends to prevent SQL from using indexes.

"

This item was migrated from the DevDiv work item tracking system [ID=371803].

Comments: Here you have a FixIntCast extension written by me and inspired by a simpler solution given at [http://www.entityframework.info/Home/SmallIntProblem](http://www.entityframework.info/Home/SmallIntProblem) - see example of usage. I've tested it on big queries with many constants and variables inside, but use at your own risk ;). ``` namespace System.Linq { /// <summary> /// author: Filip Sielimowicz inspired by /// http://www.entityframework.info/Home/SmallIntProblem /// </summary> public static class IntCastFixExtension { public static IQueryable<T> FixIntCast<T>(this IQueryable<T> q, bool narrowMemberExpr = true, bool narrowConstantExpr = true) { var visitor = new FixIntCastVisitor() { narrowConstExpr = narrowConstantExpr, narrowMembExpr = narrowMemberExpr }; Expression original = q.Expression; var expr = visitor.Visit(original); return q.Provider.CreateQuery<T>(expr); } private class FixIntCastVisitor : ExpressionVisitor { public bool narrowConstExpr; public bool narrowMembExpr; protected override Expression VisitBinary(BinaryExpression node) { bool eq = node.NodeType == ExpressionType.Equal; bool neq = node.NodeType == ExpressionType.NotEqual; if (eq || neq) { var leftUncasted = ReducePossiblyNotNecessaryIntCastExpr(node.Left); var rightUncasted = ReducePossiblyNotNecessaryIntCastExpr(node.Right); var rightConst = node.Right as ConstantExpression; if (leftUncasted == null) { return base.VisitBinary(node); } if (rightUncasted != null) { if (NarrowTypesAreCompatible(leftUncasted.Type, rightUncasted.Type)) { // Usuwamy niepotrzebne casty do intów występujące po obu stronach equalsa return eq ? Expression.Equal(leftUncasted, rightUncasted) : Expression.NotEqual(leftUncasted, rightUncasted); } } else if (rightConst != null) { // Zamiast casta argumentu z lewej w górę do inta (tak zrobił linq2entity) // zawężamy występującą po prawej stałą typu 'int' do typu argumentu z lewej if ((rightConst.Type == typeof(int) || rightConst.Type == typeof(int?))) { var value = rightConst.Value; var narrowedValue = value == null ? null : Convert.ChangeType(rightConst.Value, leftUncasted.Type); Expression narrowedConstExpr = Expression.Constant(narrowedValue, leftUncasted.Type); return eq ? Expression.Equal(leftUncasted, narrowedConstExpr) : Expression.NotEqual(leftUncasted, narrowedConstExpr); } } else if (node.Right.NodeType == ExpressionType.MemberAccess) { // Jak po prawej mamy wyrażenie odwołujące się do zmiennej typu int to robimy podobnie jak przy stałej // - zawężamy to, zamiast upcasta do inta z lewej. var rightMember = node.Right; var narrowedMemberExpr = Expression.Convert(rightMember, leftUncasted.Type); return eq ? Expression.Equal(leftUncasted, narrowedMemberExpr) : Expression.NotEqual(leftUncasted, narrowedMemberExpr); } } return base.VisitBinary(node); } private bool NarrowTypesAreCompatible(Type t1, Type t2) { if (t1 == typeof(short?)) t1 = typeof(short); if (t2 == typeof(short?)) t2 = typeof(short); if (t1 == typeof(byte?)) t1 = typeof(byte); if (t2 == typeof(byte?)) t2 = typeof(byte); return t1 == t2; } private bool IsNullable(Type t) { return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>); } private Expression CorrectNullabilityToNewExpression(Expression originalExpr, Expression newExpr) { if (IsNullable(originalExpr.Type) == IsNullable(newExpr.Type)) { return newExpr; } else { if (IsNullable(originalExpr.Type)) { Type nullableUncastedType = typeof(Nullable<>).MakeGenericType(newExpr.Type); return Expression.Convert(newExpr, nullableUncastedType); } else { Type notNullableUncastedType = Nullable.GetUnderlyingType(newExpr.Type); return Expression.Convert(newExpr, notNullableUncastedType); } } } private Expression ReducePossiblyNotNecessaryIntCastExpr(Expression expr) { var unnecessaryCast = expr as UnaryExpression; if (unnecessaryCast == null || unnecessaryCast.NodeType != ExpressionType.Convert || !(unnecessaryCast.Type == typeof(int) || unnecessaryCast.Type == typeof(int?)) ) { // Not int cast, end return null; } if ( (unnecessaryCast.Operand.Type == typeof(short) || unnecessaryCast.Operand.Type == typeof(byte) || unnecessaryCast.Operand.Type == typeof(short?) || unnecessaryCast.Operand.Type == typeof(byte?)) ) { // uncast simple int cast return CorrectNullabilityToNewExpression(unnecessaryCast, unnecessaryCast.Operand); } else { var innerUnnecessaryCast = unnecessaryCast.Operand as UnaryExpression; if (innerUnnecessaryCast == null || innerUnnecessaryCast.NodeType != ExpressionType.Convert || !(innerUnnecessaryCast.Type == typeof(int) || innerUnnecessaryCast.Type == typeof(int?)) ) { // This is not double int cast ( (int)(int?) or something ) return null; } if ( (innerUnnecessaryCast.Operand.Type == typeof(short) || innerUnnecessaryCast.Operand.Type == typeof(byte) || innerUnnecessaryCast.Operand.Type == typeof(short?) || innerUnnecessaryCast.Operand.Type == typeof(byte?)) ) { // This is doubled int cast e.g. (int)(int?) // Reduse it radically ... return CorrectNullabilityToNewExpression(unnecessaryCast, innerUnnecessaryCast.Operand); } } return null; } } } } ```

Commented Issue: Query: Cast introduced for enum properties may prevent SQL from using indexes [186]

$
0
0
"In this it might have to do with the fact that it is using function mapping (it is a TVF), but I am not sure.

var products = from p in db.ProductsByName(""%ich%"")
where p.Category == Categories.Food
select p;

I think this kind of cast tends to prevent SQL from using indexes.

"

This item was migrated from the DevDiv work item tracking system [ID=371803].

Comments: Sorry, small correction to above (arrowConstExpr and narrowConstantExpr params where not used) ``` namespace System.Linq { /// <summary> /// author: Filip Sielimowicz inspired by /// http://www.entityframework.info/Home/SmallIntProblem /// </summary> public static class IntCastFixExtension { public static IQueryable<T> FixIntCast<T>(this IQueryable<T> q, bool narrowMemberExpr = true, bool narrowConstantExpr = true) { var visitor = new FixIntCastVisitor() { narrowConstExpr = narrowConstantExpr, narrowMembExpr = narrowMemberExpr }; Expression original = q.Expression; var expr = visitor.Visit(original); return q.Provider.CreateQuery<T>(expr); } private class FixIntCastVisitor : ExpressionVisitor { public bool narrowConstExpr; public bool narrowMembExpr; protected override Expression VisitBinary(BinaryExpression node) { bool eq = node.NodeType == ExpressionType.Equal; bool neq = node.NodeType == ExpressionType.NotEqual; if (eq || neq) { var leftUncasted = ReducePossiblyNotNecessaryIntCastExpr(node.Left); var rightUncasted = ReducePossiblyNotNecessaryIntCastExpr(node.Right); var rightConst = node.Right as ConstantExpression; if (leftUncasted == null) { return base.VisitBinary(node); } if (rightUncasted != null) { if (NarrowTypesAreCompatible(leftUncasted.Type, rightUncasted.Type)) { // Usuwamy niepotrzebne casty do intów występujące po obu stronach equalsa return eq ? Expression.Equal(leftUncasted, rightUncasted) : Expression.NotEqual(leftUncasted, rightUncasted); } } else if (rightConst != null) { // Zamiast casta argumentu z lewej w górę do inta (tak zrobił linq2entity) // zawężamy występującą po prawej stałą typu 'int' do typu argumentu z lewej if (narrowConstExpr && (rightConst.Type == typeof(int) || rightConst.Type == typeof(int?))) { var value = rightConst.Value; var narrowedValue = value == null ? null : Convert.ChangeType(rightConst.Value, leftUncasted.Type); Expression narrowedConstExpr = Expression.Constant(narrowedValue, leftUncasted.Type); return eq ? Expression.Equal(leftUncasted, narrowedConstExpr) : Expression.NotEqual(leftUncasted, narrowedConstExpr); } } else if (node.Right.NodeType == ExpressionType.MemberAccess) { // Jak po prawej mamy wyrażenie odwołujące się do zmiennej typu int to robimy podobnie jak przy stałej // - zawężamy to, zamiast upcasta do inta z lewej. if (narrowMembExpr) { var rightMember = node.Right; var narrowedMemberExpr = Expression.Convert(rightMember, leftUncasted.Type); return eq ? Expression.Equal(leftUncasted, narrowedMemberExpr) : Expression.NotEqual(leftUncasted, narrowedMemberExpr); } } } return base.VisitBinary(node); } private bool NarrowTypesAreCompatible(Type t1, Type t2) { if (t1 == typeof(short?)) t1 = typeof(short); if (t2 == typeof(short?)) t2 = typeof(short); if (t1 == typeof(byte?)) t1 = typeof(byte); if (t2 == typeof(byte?)) t2 = typeof(byte); return t1 == t2; } private bool IsNullable(Type t) { return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>); } private Expression CorrectNullabilityToNewExpression(Expression originalExpr, Expression newExpr) { if (IsNullable(originalExpr.Type) == IsNullable(newExpr.Type)) { return newExpr; } else { if (IsNullable(originalExpr.Type)) { Type nullableUncastedType = typeof(Nullable<>).MakeGenericType(newExpr.Type); return Expression.Convert(newExpr, nullableUncastedType); } else { Type notNullableUncastedType = Nullable.GetUnderlyingType(newExpr.Type); return Expression.Convert(newExpr, notNullableUncastedType); } } } private Expression ReducePossiblyNotNecessaryIntCastExpr(Expression expr) { var unnecessaryCast = expr as UnaryExpression; if (unnecessaryCast == null || unnecessaryCast.NodeType != ExpressionType.Convert || !(unnecessaryCast.Type == typeof(int) || unnecessaryCast.Type == typeof(int?)) ) { // To nie jest cast na inta, do widzenia return null; } if ( (unnecessaryCast.Operand.Type == typeof(short) || unnecessaryCast.Operand.Type == typeof(byte) || unnecessaryCast.Operand.Type == typeof(short?) || unnecessaryCast.Operand.Type == typeof(byte?)) ) { // Jest cast z shorta na inta return CorrectNullabilityToNewExpression(unnecessaryCast, unnecessaryCast.Operand); } else { var innerUnnecessaryCast = unnecessaryCast.Operand as UnaryExpression; if (innerUnnecessaryCast == null || innerUnnecessaryCast.NodeType != ExpressionType.Convert || !(innerUnnecessaryCast.Type == typeof(int) || innerUnnecessaryCast.Type == typeof(int?)) ) { // To nie jest podwójny cast między intami (np. int na int?), do widzenia return null; } if ( (innerUnnecessaryCast.Operand.Type == typeof(short) || innerUnnecessaryCast.Operand.Type == typeof(byte) || innerUnnecessaryCast.Operand.Type == typeof(short?) || innerUnnecessaryCast.Operand.Type == typeof(byte?)) ) { // Mamy podwójny cast, gdzie w samym środku siedzi short // Robimy skrócenie, żeby intów nie produkował zamiast short -> int -> int? // powinno ostatecznie wychodzić short -> short czyli brak castowania w ogóle. return CorrectNullabilityToNewExpression(unnecessaryCast, innerUnnecessaryCast.Operand); } } return null; } } } } ```

Commented Issue: UpForGrabs: Query: Cast introduced in query for Int16 parameters that may prevent SQL from using indexes [823]

$
0
0
This is a very similar issue to [186](http://entityframework.codeplex.com/workitem/186) and [187](http://entityframework.codeplex.com/workitem/187):

Model contains this class:

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public short Part { get; set; }
}

A query like this:
```
short param = 1;
var q = db.Products.Where(c => c.Part == param);

```
Gets a translation like this:
```
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent1].[Part] AS [Part],
[Extent1].[ReferralUrl] AS [ReferralUrl]
FROM [dbo].[Products] AS [Extent1]
WHERE CAST([Extent1].[Part] AS int) = @p__linq__0)

```
Although both the parameters and the column are of type Int16. As a consequence of this, there is now way a database server such as SQL Server can take advantage of an index over Products.Part.
Comments: If something still goes wrong, see more complex version of FixIntCast shown here: http://stackoverflow.com/questions/9016265/generated-query-for-tinyint-column-introduces-a-cast-to-int This includes modifications to equals/not equals expressions: - reduction of possibly unnecessary doubled int casts, like (int?)(int)(short) -> (short?) - reduction of possibly unnecessary casts of constant expressions (change to: narrow int constants to short/byte) - reduction of possibly unnecessary casts of member expressions (change to: narrow int memb expression to short/byte)

Commented Unassigned: After upgrade to 6.1.1 columns are renamed by code first migration [2500]

$
0
0
After an upgrade from EF 6.1.0 to 6.1.1 my application complained about a changed model and required an explicit migration. However, to my suprise, it wasn't simply a small change in something like a default length or any other 'non fundamental' change. No, it wanted to switch a few columns.
Currently I'm thinking it is only occurring in classes where multiple relations to a single other entity exist (In th example below; both Branch and Customer are an Organization with an exposed FK in Assignment)

One of those would be (cut out some others):
public override void Up()
{
DropIndex("dbo.Assignments", new[] { "CustomerId" });
DropIndex("dbo.Assignments", new[] { "BranchId" });

RenameColumn(table: "dbo.Assignments", name: "CustomerId", newName: "__mig_tmp__0");
RenameColumn(table: "dbo.Assignments", name: "BranchId", newName: "CustomerId");
RenameColumn(table: "dbo.Assignments", name: "__mig_tmp__0", newName: "BranchId");

AlterColumn("dbo.Assignments", "BranchId", c => c.Guid());
AlterColumn("dbo.Assignments", "CustomerId", c => c.Guid(nullable: false));

CreateIndex("dbo.Assignments", "CustomerId");
CreateIndex("dbo.Assignments", "BranchId");
}

The code of Assignment was not changed at all so I'm quite confident that a change in the migration logic is causing this altered interpretation.

All thoughts, work-arounds/solutions/etc., are most welcome.
Comments: I've created a very basic project which contains what is needed to reproduce the problem. The zip should contain everything to reproduce. The connection string in the config isn't correct and I removed the packages so it is a somewhat smaller zip. Steps I took (in Package Manager Console): - Enable-Migrations - Add-Migration "Initial" - Update-Database - Install-Package EntityFramework -Version 6.1.1 - Add-Migration "After EF Upgrade" - Update-Database Steps to reproduce in this project (indefinitely): [if @ version 6.1.1] - Install-Package EntityFramework -Version 6.1.0 [else] - Install-Package EntityFramework -Version 6.1.1 - Add-Migration "Random name" - Update-Database

New Post: OrderBy isn't taking affect

$
0
0
Hello there

I have a simple Entity Framework query like so
var query = (from c in context.accounts_companies
                  select new AccountSearchResultModel()
{
LastContacted = (from calc in context.communique_accounts_last_contacts
                                                  where calc.account_id == companyId
                                                  orderby calc.last_contact_date descending
                                                  select calc.last_contact_date).FirstOrDefault())

});
However my query is never ordered at all, how can I order by last_contact_date?

Edited Task: Make sure we don't ship runtime builds created using the Roslyn C# compiler yet [2556]

$
0
0
We had a customer report that indicates that there is at least one pre-release package of EF 6.1.2 in the wild that was built using the Roslyn C# compiler.

There are a few known breaking changes (and potentially some unknown bugs) in the pre-release version of the new compiler. We should not take a dependency on it yet to build our runtime, at least not the versions that we ship to customers.


Commented Task: Make sure we don't ship runtime builds created using the Roslyn C# compiler yet [2556]

$
0
0
We had a customer report that indicates that there is at least one pre-release package of EF 6.1.2 in the wild that was built using the Roslyn C# compiler.

There are a few known breaking changes (and potentially some unknown bugs) in the pre-release version of the new compiler. We should not take a dependency on it yet to build our runtime, at least not the versions that we ship to customers.

Comments: I've decompiled the EntityFramework.dll from the nupkg packages laid down by our VS14 MSI and seen the different MethodInfos created to back the delegates under Roslyn and under non-Roslyn compilers. The release-6.1.2-beta1 frozen runtime does not contain the Roslyn-type MethodInfo and so does not cause the problem. There was an error in picking up the frozen runtime correctly. But I've confirmed that is fixed in the nightly builds as of 10/16/14. Also I've set up some MSIViabilityChecks to check that we what we produce for nightly builds contains an EntityFramework.dll with the same AssemblyVersionInfo number as the frozen runtime (checkin #444dbfe). Note also Andriy checked in a fix for the specific issue which was causing problems in QueryableExtensions - see https://entityframework.codeplex.com/workitem/2557.

Commented Unassigned: CloneDbCommand throws Exception in 6.1.2-beta1 [2554]

$
0
0
Dear Sirs,

the CloneDBCommand throws an Exception if one uses EF together with StackExchange MiniProfiler:

```
Any exception caught System.InvalidCastException: Das Objekt des Typs "StackExchange.Profiling.Data.ProfiledDbCommand" kann nicht in Typ "System.Data.SqlClient.SqlCommand" umgewandelt werden.
bei System.Data.Entity.SqlServer.SqlProviderServices.CloneDbCommand(DbCommand fromDbCommand)
bei System.Data.Entity.Core.Common.DbCommandDefinition.CreateCommand()
bei EFCache.CachingCommandDefinition.CreateCommand()
bei System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.PrepareEntityCommandBeforeExecution(EntityCommand entityCommand)
bei System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
bei System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
bei System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
bei System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
bei System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
bei System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
bei System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__0[TResult](IEnumerable`1 sequence)
bei System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
bei System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
bei System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
bei System.Linq.Queryable.First[TSource](IQueryable`1 source)
```

There was no problem in EF 6.1.1.

With best regards

Rufus
Comments: We could add a fallback logic to compensate for other providers that follow similar paradigm - check if the command passed to CloneDbCommand is actually SqlCommand and if not, use default clone mechanism instead. Assigning to Lawrence

Edited Issue: CloneDbCommand throws Exception in 6.1.2-beta1 [2554]

$
0
0
Dear Sirs,

the CloneDBCommand throws an Exception if one uses EF together with StackExchange MiniProfiler:

```
Any exception caught System.InvalidCastException: Das Objekt des Typs "StackExchange.Profiling.Data.ProfiledDbCommand" kann nicht in Typ "System.Data.SqlClient.SqlCommand" umgewandelt werden.
bei System.Data.Entity.SqlServer.SqlProviderServices.CloneDbCommand(DbCommand fromDbCommand)
bei System.Data.Entity.Core.Common.DbCommandDefinition.CreateCommand()
bei EFCache.CachingCommandDefinition.CreateCommand()
bei System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.PrepareEntityCommandBeforeExecution(EntityCommand entityCommand)
bei System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
bei System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
bei System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
bei System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
bei System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
bei System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
bei System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
bei System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__0[TResult](IEnumerable`1 sequence)
bei System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
bei System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
bei System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
bei System.Linq.Queryable.First[TSource](IQueryable`1 source)
```

There was no problem in EF 6.1.1.

With best regards

Rufus

Commented Unassigned: TruncateTime in EntityFunctions (add format as parameter) [2503]

$
0
0
Hello!

You have a method __TruncateTime__ in __DbFunctions (EntityFunctions)__ class. It calls __HandleCanonicalFunctionTruncateTime__ in __SqlFunctionCallHandler__, that generate a sql statement for this function. It has a hard-coded format param '__102__'. I have a proposal to allow passing that param to method. The SQL Server function __CONVERT__, that you use in this method, allows to change format.
Comments: @Gromilich: Sorry if it has taken some time for us to answer. TruncateTime is what we call a canonical function. EF providers are required to implement canonical functions, therefore: 1. Making changes to the set of canonical functions that EF supports is a big deal for compatibility, e.g. changing the signature of an existing function is practically impossible without breaking all existing providers, and adding a new canonical function (or a new overload) is practically impossible without making existing providers somewhat obsolete. 2. We cannot have a SQL Server-specific parameter in a canonical function, e.g. the meaning of the format passed to the CONVERT function cannot be a parameter on a canonical function. Given the reasons above we could not take this change on a canonical function, but we could still consider accepting something like this as a SQL Server specific function. Depending on the implementation you would need to: 1. Add it to ProviderManifest.XML file in the SQL Server EF provider 2. Add it to SqlFunctions class (to make it available to LINQ queries) 3. Add any logic to generate SQL (this would be needed because the function name will not map directly to an actual built-in function in SQL) to a function handler in SqlFunctionCallHandler. I should mention, just in case, that the EF team is not planning to do this but we are open to consider taking a pull request if you want to contribute the improvement. HTH, Diego

Edited Feature: TruncateTime in EntityFunctions (add format as parameter) [2503]

$
0
0
Hello!

You have a method __TruncateTime__ in __DbFunctions (EntityFunctions)__ class. It calls __HandleCanonicalFunctionTruncateTime__ in __SqlFunctionCallHandler__, that generate a sql statement for this function. It has a hard-coded format param '__102__'. I have a proposal to allow passing that param to method. The SQL Server function __CONVERT__, that you use in this method, allows to change format.

Commented Feature: TruncateTime in EntityFunctions (add format as parameter) [2503]

$
0
0
Hello!

You have a method __TruncateTime__ in __DbFunctions (EntityFunctions)__ class. It calls __HandleCanonicalFunctionTruncateTime__ in __SqlFunctionCallHandler__, that generate a sql statement for this function. It has a hard-coded format param '__102__'. I have a proposal to allow passing that param to method. The SQL Server function __CONVERT__, that you use in this method, allows to change format.
Comments: __Note for triage:__ This sounds like it would be generally useful and it is possible that we can get a pull request with this improvement (a canonical function is out of the question but a SQL Server-specific function would work for this). I will mark the issue as "UpForGrabs" and I propose we move it to Future.

Edited Feature: UpForGrabs: TruncateTime in EntityFunctions (add format as parameter) [2503]

$
0
0
Hello!

You have a method __TruncateTime__ in __DbFunctions (EntityFunctions)__ class. It calls __HandleCanonicalFunctionTruncateTime__ in __SqlFunctionCallHandler__, that generate a sql statement for this function. It has a hard-coded format param '__102__'. I have a proposal to allow passing that param to method. The SQL Server function __CONVERT__, that you use in this method, allows to change format.

Edited Feature: UpForGrabs: TruncateTime with format parameter in SqlFunctions [2503]

$
0
0
Hello!

You have a method __TruncateTime__ in __DbFunctions (EntityFunctions)__ class. It calls __HandleCanonicalFunctionTruncateTime__ in __SqlFunctionCallHandler__, that generate a sql statement for this function. It has a hard-coded format param '__102__'. I have a proposal to allow passing that param to method. The SQL Server function __CONVERT__, that you use in this method, allows to change format.

Edited Issue: Unable to create EntityType with a BaseType [2499]

$
0
0
It is currently impossible to create an `EntityType` instance with a value for the `BaseType` property.

Commented Issue: Unable to create EntityType with a BaseType [2499]

$
0
0
It is currently impossible to create an `EntityType` instance with a value for the `BaseType` property.
Comments: @fejesjoco: thanks for reporting this. We will consider fixing this for EF 6.1.2, although I am not sure what the fix looks like. I have assigned it.

Source code checked in, #d9517e90117ec6104c52792cdc56f31088c34575

$
0
0
Handle embedded expression references. Adds ability to execute expression factories or reference expression member/properties when embedded into a ELinq expression. Adds handling of closure member access by executing access and using result as a constant expression.

Source code checked in, #bafa48e6987441e8b823e6970d44bb3996ea1934

$
0
0
Remove use of DynamicInvoke where unnecessary, add 4 negative tests.
Viewing all 10318 articles
Browse latest View live




Latest Images