Quantcast
Channel: entityframework Issue Tracker Rss Feed
Viewing all 9566 articles
Browse latest View live

Commented Issue: Migrationing from EF5 to 6.1.2 fails for SqlCE (follow-up on #2659) [2807]

$
0
0
Reporting this to note that [work item #2659](https://entityframework.codeplex.com/workitem/2659) has __not__ been resolved for all use cases.

We ship a desktop application using EF and SQL CE and perform migrations programmatically as needed - we can't easily perform a disjointed upgrade (going from 5 to 6 to 6.1.2, migrating at each step) as the work item resolution suggests. It would be much more more helpful if the migration table code was updated to cover all historical scenarios.

It looks like I'll have to stick with EF 5.0.0 until there are newer versions that can actually cleanly support upgrading.
Comments: __EF Team Triage:__ Agreed - you should be able to go from 5 -> 6.x. Assigning to 6.2 to add logic to detect and support a v5 -> vCurrent upgrade.

Closed Unassigned: The StringLengthAttribute is not honoring MinimumLength [2808]

$
0
0
I have a simple code-first project. In one of the POCO objects, I have the following property:

```
[Required]
[StringLength(3, MinimumLength = 3)]
public string TestString { get; set; }
```
I expected the Add-Migration command to create the following output:
```
TestString = c.String(nullable: false, maxLength: 3, fixedLength: true),
```
However, I get the following output:
```
TestString = c.String(nullable: false, maxLength: 3),
```
I've check the StringLengthAttribute for any property that would allow me to specify a fix length but there isn't any. Therefore, (IMHO) FixedLength should be set using code something like this:

```
FixedLength = MaximumLength == MinimumLength;
```

Comments: __EF Team Triage:__ Discussed and agreed that we don't want to opt into a fixed length column. If the database truly enforced that 3 characters of data were sent to the database, then it may be a good choice... but if you send 2 characters then SQL Server will just pad the data with spaces (so it provides little-to-no value).

Closed Unassigned: With Oracle, Where clause with a Contains having more than 1000 values is ignoring the 1001th value [2810]

$
0
0

EDIT: The problem is due to the Oracle provider, not Entity Framework...

With Entity Framework 6.1.3 with Oracle.

When having a Where clause with more than 1000 values (ex. 3500 ), Entity Framework is splitting the values because with Oracle, the maximum number of items in a "IN" clause is 1000.

So the generated query is something like :

```
Where Extent1.MyId IN (1,2,3,... 1000) OR IN (1002,1003,.... 2000) ...
```

Every 1000 values, the 1001th is ignored...




Comments: __EF Team Triage:__ The Oracle provider is built and supported by Oracle (rather than the EF team). You could follow up with Oracle at https://community.oracle.com.

Edited Issue: UpForGrabs: Inconsistent behavior for related entities in AddOrUpdate depending on whether root entity is new or existing [2128]

$
0
0
Working with a common many-to-many scenario, code first, EF 6.02.

```
Product >-< Category
```

I have a context with `MigrateDatabaseToLatestVersion` initializer. In the configurations's `Seed` method I add a few products and categories and establish the many to many by adding products to `Category.Products`.

The essential code (where `db` is a `DbContext`):

```
db.Products.AddOrUpdate(x => x.Name, p1, p2, p3, p4, p5, p6); // p1 etc. are products
var shoes = db.Categories.Create();
// set properties

shoes.Products.Add(p1);
shoes.Products.Add(p4);
shoes.Products.Add(p6);

// More categories

db.Categories.AddOrUpdate(x => x.CategoryName, sports, accessories, shoes);
```

When the database is created everything is fine.

__With an existing database__ I try to add a new product in an existing category. This code runs after the code above, before the `SaveChanges` call.

```
var p7 = db.Products.Create();
db.Products.AddOrUpdate(x => x.Name, p7);
shoes.Products.Add(p7)
```

The result is that the new product is saved, but not the many to many association. This is because at this point, `shoes` is in a `Detached` state, so the change tracker doesn't notice the addition.

Now if instead of `shoes.Products.Add` I do

```
p7.Categories.Add(shoes);
```

the association is saved, but _all existing products in `shoes` are duplicated_. I understand that this is because `shoes`, and all its products, are marked as `Added`.

If I do

```
db.Entry(shoes).State = EntityState.Unchanged;
```

I get a duplicate key exception, which I don't understand, because `shoes` is `Detached`.

The only way I'm aware of to get this working is

```
shoes = db.Categories.Single(c => c.CategoryName == shoes.CategoryName);
shoes.Products.Add(p7);
```

So, finally, my question. You guys probably have good reasons not to attach existing entities in an `AddOrUpdate` call. However, the above scenario would become much more transparent and intuitive if it _did_ attach existing entities.

It's probably a big issue to change this behavior, but could it be an optional feature of `AddOrUpdate`, as a third parameter `attachExisting`?

Commented Issue: UpForGrabs: Inconsistent behavior for related entities in AddOrUpdate depending on whether root entity is new or existing [2128]

$
0
0
Working with a common many-to-many scenario, code first, EF 6.02.

```
Product >-< Category
```

I have a context with `MigrateDatabaseToLatestVersion` initializer. In the configurations's `Seed` method I add a few products and categories and establish the many to many by adding products to `Category.Products`.

The essential code (where `db` is a `DbContext`):

```
db.Products.AddOrUpdate(x => x.Name, p1, p2, p3, p4, p5, p6); // p1 etc. are products
var shoes = db.Categories.Create();
// set properties

shoes.Products.Add(p1);
shoes.Products.Add(p4);
shoes.Products.Add(p6);

// More categories

db.Categories.AddOrUpdate(x => x.CategoryName, sports, accessories, shoes);
```

When the database is created everything is fine.

__With an existing database__ I try to add a new product in an existing category. This code runs after the code above, before the `SaveChanges` call.

```
var p7 = db.Products.Create();
db.Products.AddOrUpdate(x => x.Name, p7);
shoes.Products.Add(p7)
```

The result is that the new product is saved, but not the many to many association. This is because at this point, `shoes` is in a `Detached` state, so the change tracker doesn't notice the addition.

Now if instead of `shoes.Products.Add` I do

```
p7.Categories.Add(shoes);
```

the association is saved, but _all existing products in `shoes` are duplicated_. I understand that this is because `shoes`, and all its products, are marked as `Added`.

If I do

```
db.Entry(shoes).State = EntityState.Unchanged;
```

I get a duplicate key exception, which I don't understand, because `shoes` is `Detached`.

The only way I'm aware of to get this working is

```
shoes = db.Categories.Single(c => c.CategoryName == shoes.CategoryName);
shoes.Products.Add(p7);
```

So, finally, my question. You guys probably have good reasons not to attach existing entities in an `AddOrUpdate` call. However, the above scenario would become much more transparent and intuitive if it _did_ attach existing entities.

It's probably a big issue to change this behavior, but could it be an optional feature of `AddOrUpdate`, as a third parameter `attachExisting`?
Comments: Moving to 6.2.0 for us to look at

Commented Unassigned: Attribute uniqueidentifier PK with ROWGUIDCOL [2796]

$
0
0
Hello!

If the PK is of type ROWGUIDCOL it should be attributed with ROWGUIDCOL in the synthesized SQL code.


Best regards,

Henrik Dahl

Comments: I think that [Creating and Modifying Identifier Columns](https://technet.microsoft.com/en-us/library/aa933115(v=sql.80).aspx) gives further information and it's not limited to something with File Stream. It's very interesting that you don't find Merge Replication relevant. I find product maturity relevant and it obviously requires replication. Many tenders require this. We have always used PKs as I wrote and as the article I just referred to states. It's just ordinary best practice, that if the PK is of type uniqueidentifier and the SQL Server generates the value, then the column should be marked with ROWGUIDCOL and if you Google for: "entity framework rowguidcol" you can see, that several others complain that EF doesn't include ROWGUIDCOL. It can obviously seem strange that it's necessary to explicitly state "ROWGUIDCOL" as it appears to be redundant in the definition of the column, as the article lets to understand. I think the right solution would be if you trivially would specify ROWGUIDCOL for a PK of type uniqueidentifier, particularly if the concrete value is generated by the database. I don't think you can find any benefit of not putting ROWGUIDCOL or can you? We can also not exclude, that the SQL Server may be doing various optimizations by having the additional meta-information which ROWGUIDCOL brings. Best regards, Henrik Dahl

Commented Unassigned: Introduce SparseAttribute attribute [2805]

$
0
0
I would like to suggest introduction of a SparseAttribute, like if I have this code:

```
public class HenrikDahlsClassForShowingRowanMiller
{
public Guid ID { get; set; }

[Timestamp]
public byte[] Version { get; set; }

[Sparse]
public Guid? NonPKGuid { get; set; }
}

```
This SQL should be generated:
```
CREATE TABLE [NonSpecifiedSchema].[HenrikDahlsClassForShowingRowanMillers] (
[ID] [uniqueidentifier] ROWGUIDCOL NOT NULL DEFAULT newsequentialid(),
[Version] rowversion NOT NULL,
[NonPKGuid] [uniqueidentifier] SPARSE,
CONSTRAINT [PK_NonSpecifiedSchema.HenrikDahlsClassForShowingRowanMillers] PRIMARY KEY ([ID])
)
```
[Documentation](https://msdn.microsoft.com/en-us/library/cc280604(v=sql.120).aspx)


Best regards,

Henrik Dahl

Comments: What do you think of this: When multiple types in an inheritance hierarchy go to the same table, this causes that the columns specific to the classes will become sparse or you don't agree on this?

Created Unassigned: EF 6.1.3 slow startup time for simple database [2811]

$
0
0
Hi!
I've created simple console application to test if EF is faster than NH especially for first query. Solution is in attachment. The problem is that this test app takes around 8 seconds to finish. I've read a lot already about slow start for EF, but I can't believe that it takes so long for such a simple application....

Can you download it and test it on your machine ?

I'm running Win 7 x64 (8GB RAM, i5-4200U, vs 2015 Community and mssql express 2014 installed on ssd, while project files are on hdd)

Commented Unassigned: Could not load file or assembly EntityFramework Version 5.0.0.0 [2788]

$
0
0
If I try the EF [Code First Migration sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) with the EF 5.0.0 NuGet package I can create the initial database without problems. At the moment I use the Enable-Migrations command I get the following error message:

PM> Enable-Migrations
Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load file or assembly 'EntityFramework, Version=5.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified."
At C:\Projects\MigrationsDemo\packages\EntityFramework.5.0.0\tools\EntityFramework.psm1:431 char:5
+ $domain.CreateInstanceFrom(
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileNotFoundException

When I update the solution to use an EF 6 NuGet package it works. I noticed this error when I tried to deploy the NuGet Gallery database and I can't upgrade to EF 6 to bypass the error for this project. This error is reported as an [issue](https://github.com/NuGet/NuGetGallery/issues/2592) at the NuGet Gallery GitHub project page by another user and you can also find my research results there. The EF 5 sample works when you use VS 2013 update 4.

Reproduction path:
Start with a VS2013 update 4 and follow the steps reported in the [sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) but use Install-Package EntityFramework -Version 5.0.0 as the command for installing EF 5. Create the initial database and enable migrations. You will see that this works. Remove the Migrations code from your solution and upgrade Visual Studio with update 5. Try to enable migrations again. At that moment you will get the reported error message.

Note: I reported this issue also on [Microsoft Connect](https://connect.microsoft.com/VisualStudio/feedback/details/1593363/ef-5-0-0-code-first-migrations-doesnt-work-after-upgrading-to-vs2013-5-error-could-not-load-file-or-assembly-entityframework-version-5-0-0-0) for the Visual Studio product group but they closed it with the reason external so I reposted it here.
Comments: I ran into this issue today, not sure if its related to yours or not, but the error is identical. Enabling Fusion Logging, I tracked it down to a config setting in %LOCALAPPDATA%\Microsoft\VisualStudio\14.0\devenv.exe.config It contained the following ``` <dependentAssembly> <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral"/> <codeBase version="5.0.0.0" href="C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\CommonExtensions\Microsoft\EFTools\NuGet Packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll"/> </dependentAssembly> ``` The "NuGet Packages" folder in EFTools didn't exist and this was what cause the error. Creating the folder and copying in a copy of the EntityFramework.5.0.0 folder from the standard nuget package installation fixed the error. Also, uninstalling the "Entity Framework 6.1.3 Tools for Visual Studio 2013" also removed the config setting and fixed the error. The same problem is also occuring in VS2015 for me as well with the same symptoms, just slightly different paths for the config and the EFTools path in the config.

Commented Unassigned: Could not load file or assembly EntityFramework Version 5.0.0.0 [2788]

$
0
0
If I try the EF [Code First Migration sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) with the EF 5.0.0 NuGet package I can create the initial database without problems. At the moment I use the Enable-Migrations command I get the following error message:

PM> Enable-Migrations
Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load file or assembly 'EntityFramework, Version=5.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified."
At C:\Projects\MigrationsDemo\packages\EntityFramework.5.0.0\tools\EntityFramework.psm1:431 char:5
+ $domain.CreateInstanceFrom(
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileNotFoundException

When I update the solution to use an EF 6 NuGet package it works. I noticed this error when I tried to deploy the NuGet Gallery database and I can't upgrade to EF 6 to bypass the error for this project. This error is reported as an [issue](https://github.com/NuGet/NuGetGallery/issues/2592) at the NuGet Gallery GitHub project page by another user and you can also find my research results there. The EF 5 sample works when you use VS 2013 update 4.

Reproduction path:
Start with a VS2013 update 4 and follow the steps reported in the [sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) but use Install-Package EntityFramework -Version 5.0.0 as the command for installing EF 5. Create the initial database and enable migrations. You will see that this works. Remove the Migrations code from your solution and upgrade Visual Studio with update 5. Try to enable migrations again. At that moment you will get the reported error message.

Note: I reported this issue also on [Microsoft Connect](https://connect.microsoft.com/VisualStudio/feedback/details/1593363/ef-5-0-0-code-first-migrations-doesnt-work-after-upgrading-to-vs2013-5-error-could-not-load-file-or-assembly-entityframework-version-5-0-0-0) for the Visual Studio product group but they closed it with the reason external so I reposted it here.
Comments: Bah sorry that was the %LOCALAPPDATA%\Microsoft\VisualStudio\12.0\devenv.exe.config for 2013

Commented Unassigned: Could not load file or assembly EntityFramework Version 5.0.0.0 [2788]

$
0
0
If I try the EF [Code First Migration sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) with the EF 5.0.0 NuGet package I can create the initial database without problems. At the moment I use the Enable-Migrations command I get the following error message:

PM> Enable-Migrations
Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load file or assembly 'EntityFramework, Version=5.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified."
At C:\Projects\MigrationsDemo\packages\EntityFramework.5.0.0\tools\EntityFramework.psm1:431 char:5
+ $domain.CreateInstanceFrom(
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileNotFoundException

When I update the solution to use an EF 6 NuGet package it works. I noticed this error when I tried to deploy the NuGet Gallery database and I can't upgrade to EF 6 to bypass the error for this project. This error is reported as an [issue](https://github.com/NuGet/NuGetGallery/issues/2592) at the NuGet Gallery GitHub project page by another user and you can also find my research results there. The EF 5 sample works when you use VS 2013 update 4.

Reproduction path:
Start with a VS2013 update 4 and follow the steps reported in the [sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) but use Install-Package EntityFramework -Version 5.0.0 as the command for installing EF 5. Create the initial database and enable migrations. You will see that this works. Remove the Migrations code from your solution and upgrade Visual Studio with update 5. Try to enable migrations again. At that moment you will get the reported error message.

Note: I reported this issue also on [Microsoft Connect](https://connect.microsoft.com/VisualStudio/feedback/details/1593363/ef-5-0-0-code-first-migrations-doesnt-work-after-upgrading-to-vs2013-5-error-could-not-load-file-or-assembly-entityframework-version-5-0-0-0) for the Visual Studio product group but they closed it with the reason external so I reposted it here.
Comments: I've tracked it down in the source code to https://entityframework.codeplex.com/SourceControl/latest#src/EFTools/EntityDesignPackage/PkgDefData/Microsoft.Data.Entity.Design.Package.pkgdef ```` // Enables the EntityDataSource connection wizard to work against Entity Framework 5 by registering a dependency // assembly codebase in the registry to hint Visual Studio (or its express flavors) as to where to go look for // the Entity Framework assembly when version 5 is required. [$RootKey$\RuntimeConfiguration\dependentAssembly\codeBase\{29A768DC-8850-4C53-BC56-32D9E7925E00}] "Name"="EntityFramework" "PublicKeyToken"="b77a5c561934e089" "Culture"="neutral" "Version"="5.0.0.0" "CodeBase"="$PackageFolder$\NuGet Packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll" ````

Commented Unassigned: Could not load file or assembly EntityFramework Version 5.0.0.0 [2788]

$
0
0
If I try the EF [Code First Migration sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) with the EF 5.0.0 NuGet package I can create the initial database without problems. At the moment I use the Enable-Migrations command I get the following error message:

PM> Enable-Migrations
Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load file or assembly 'EntityFramework, Version=5.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified."
At C:\Projects\MigrationsDemo\packages\EntityFramework.5.0.0\tools\EntityFramework.psm1:431 char:5
+ $domain.CreateInstanceFrom(
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileNotFoundException

When I update the solution to use an EF 6 NuGet package it works. I noticed this error when I tried to deploy the NuGet Gallery database and I can't upgrade to EF 6 to bypass the error for this project. This error is reported as an [issue](https://github.com/NuGet/NuGetGallery/issues/2592) at the NuGet Gallery GitHub project page by another user and you can also find my research results there. The EF 5 sample works when you use VS 2013 update 4.

Reproduction path:
Start with a VS2013 update 4 and follow the steps reported in the [sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) but use Install-Package EntityFramework -Version 5.0.0 as the command for installing EF 5. Create the initial database and enable migrations. You will see that this works. Remove the Migrations code from your solution and upgrade Visual Studio with update 5. Try to enable migrations again. At that moment you will get the reported error message.

Note: I reported this issue also on [Microsoft Connect](https://connect.microsoft.com/VisualStudio/feedback/details/1593363/ef-5-0-0-code-first-migrations-doesnt-work-after-upgrading-to-vs2013-5-error-could-not-load-file-or-assembly-entityframework-version-5-0-0-0) for the Visual Studio product group but they closed it with the reason external so I reposted it here.
Comments: That was added as part of https://entityframework.codeplex.com/SourceControl/changeset/290e8d92f38de13c6df5b054911da70663dc2e19 But the commit doesn't include anything to ensure that this "NuGet Packages\EntityFramework.5.0.0" folder is created.

Commented Feature: [UpForGrabs] [Performance] Reduce start up time by loading finished Code First models from a persistent cache [1876]

$
0
0
Building and compiling large models using the Code First pipeline can be expensive in terms of start up time. Several pieces are coming together that could allow us to serialize the output of Code First (including the O-C mapping) into an XML artifact and then to deserialize it directly on subsequent runs.

Creating an efficient and completely reliable way of verifying that the serialized version of the model actually matches the Code First model doesn't seem feasible, but there are simple heuristics, e.g. checking for file timestamps of the assembly containing the model and the timestamp of the XML artifact that should work reasonably well in common scenarios.

Initial tests with a hacky prototype show that start up time of a model with 100 entities can do down from 8 seconds to 2 seconds using this approach.
Comments: I've been working through the known issues found around the web with the patch code, and adding test coverage to try to get the code into a state that it might be accepted as a pull request. I would like for more users to try out the [updated code](https://entityframework.codeplex.com/SourceControl/network/forks/jEdge/CodeFirstCache) with their various context configurations so we can get this working for everyone. The NugetPackages folder in [my fork](https://entityframework.codeplex.com/SourceControl/network/forks/jEdge/CodeFirstCache) contains the packaged (unsigned) EntityFramework build with my changes to allow easier testing with a [local NuGet feed](https://docs.nuget.org/create/hosting-your-own-nuget-feeds). I have a [discussion for this item](http://entityframework.codeplex.com/discussions/642552) if anyone has feedback on the fork. I work with a very large data model and this improvement would save us on the order of 10-12 seconds of startup time, so I want this to be successful. Thank you.

Commented Unassigned: Allow generating migration code for a custom MigrationOperation from CSharpMigrationCodeGenerator [2799]

$
0
0
Currently, the CSharpMigrationCodeGenerator must have a specific Generate method for each specific MigrationOperation in the migration. If there is a custom MigrationOperation in the list of migrations, it falls back to the Generate method for the AddColumnOperation, which fails with the following exception:

_The best overloaded method match for 'System.Data.Entity.Migrations.Design.CSharpMigrationCodeGenerator.Generate(System.Data.Entity.Migrations.Model.AddColumnOperation, System.Data.Entity.Migrations.Utilities.IndentedTextWriter)' has some invalid arguments_

The CSharpMigrationCodeGenerator should work more like the SqlServerMigrationSqlGenerator, where there is a virtual Generate method for MigrationOperation:
```
protected virtual void Generate(MigrationOperation migrationOperation)

```
As:
```
protected virtual void Generate(MigrationOperation migrationOperation, IndentedTextWriter writer)

```
In this way, developers could override this virtual method when creating a class that derives from CSharpMigrationCodeGenerator the same way it is currently possible with the SqlServerMigrationSqlGenerator class.

Without this, the workaround is to either reimplement the CSharpMigrationCodeGenerator or skip the code migration step for custom migration operations and translate each into a SqlOperation.

As a side note, since there is already a GetDefaultNamespaces virtual method, we can register any custom namespaces required to support the custom MigrationOperation types, so there is no issue with the migration class being generated with broken references.

-- Travis Schettler
Comments: Thanks Rowan, For what I currently need, just having the ability to generate code for a custom ```MigrationOperation``` is enough. I am adding the operations to the migration operation list within a custom code generator deriving from ```CSharpMigrationCodeGenerator```, prior to calling ```base.Generate```. I do see how opening up ```ModelDiffer``` could be beneficial for adding the custom migration to the list as the migration operations are initially determined. -- Travis

Commented Unassigned: The StringLengthAttribute is not honoring MinimumLength [2808]

$
0
0
I have a simple code-first project. In one of the POCO objects, I have the following property:

```
[Required]
[StringLength(3, MinimumLength = 3)]
public string TestString { get; set; }
```
I expected the Add-Migration command to create the following output:
```
TestString = c.String(nullable: false, maxLength: 3, fixedLength: true),
```
However, I get the following output:
```
TestString = c.String(nullable: false, maxLength: 3),
```
I've check the StringLengthAttribute for any property that would allow me to specify a fix length but there isn't any. Therefore, (IMHO) FixedLength should be set using code something like this:

```
FixedLength = MaximumLength == MinimumLength;
```

Comments: Please reconsider, because I think you have missed the point I was trying to make. First, I agree that the database should NOT be in the business of validating the minimum length of any string. Second, as you know, SQL provides many types, including VARIABLE and FIXED length strings. And we all know, a fixed length string has better performance than a variable length string. (see: [here](https://social.msdn.microsoft.com/forums/sqlserver/en-US/47bfe0ed-daf0-4cd3-bfbd-ca0c17044853/which-is-best-in-performance-char-or-varchar), [here](https://ask.sqlservercentral.com/questions/20960/char-vs-varchar-index-performance.html) or [here](http://www.sql-server-performance.com/2007/datatypes/)). From a pure EF code-first approach, developers SHOULD be able to define their database types from their data model; otherwise, Entity Framework "provides little-to-no value". Let say that a given domain calls for a property to be of fixed length. For example: the Foreign Exchange markets uses a fixed length symbol of 6 characters, like: USDJPY or EURUSD. From a C# language standpoint, this requirement could be implemented as an array of 6 characters ```char[6]``` or a string (which is normally easier to work with). From a database storage standpoint, a FIXED length string (```CHAR(6)```) would be more efficient than a ```VARCHAR(6)```. Third, your statement assumes that no validation has occurred. Where in fact, any "real-world" project would require validation. Which is normally performed in one or more places; such as the GUI layer, transport layer (like ASP.NET), or (at the minimum) the business layer. Using attributes, like the ones found in ```System.ComponentModel.DataAnnotations``` would make automating the validation logic easier. In keeping with the DRY principle, the developer should only have to define a rule once. And the best place to define these types of rules are on the POCO object itself. like so: Simple Example (lines added for clarity): ``` public class Symbol { // Used by validation logic but only the max value is support by the EF logic [StringLength(3, MinimumLength = 3)] // --- or written this way --- // Used by validation and EF logic [Max(3)] // Used by validation logic (and should be respected by EF, but currently is not) [Min(3)] // Used by validation logic (depending on the context, may or may not be used by EF) [Required] public string Name {get; set;} } ``` To implement this correctly today, requires placing this "fixed length" rule in two places. One on the POCO object (as shown above) and the other in a EF specific mapping - to FORCE Entity Framework to do the RIGHT THING, like so: ``` modelBuilder.Entity<Symbol>().Property(e => e.Name).IsFixedLength(); ``` Why all the hoops? The less 'custom' mappings (or defining a rule in multiple places) the better! In summary, (in MHO) there are two problems here: 1. The inconsistent use of attributes. I.e. what attributes EF supports and which properties of these supported attribute it chooses to honor is a mystery. EF touts "by conventions" but in this case it is creating "tribe knowledge". It would have been better NOT to support the StringLength attribute than to only support half of it. At least that way we would know what to expect. 2. Requiring the developer to jump through unnecessary hoops. Therefore, I'm asking the EF team to better support us developers by add support for both StringLength's MinimumLength __and__ the MinAttribute.

Created Unassigned: infinity loop in DetectChangesInForeignKeys [2812]

$
0
0
Ef 6.1.3
Project - ASP NET app (azure web role)

And new data not saved to db - this code:
ctx.BindSnMetrics.Add((BindSnMetric)entity)
never ends
1 hour no one uses my app, but it use 30% of cpu

I have a dump (160MB rar) - can't attach it (4mb max) (maybe i can send by email)


Bugged thread callstack:

EntityFramework.dll!System.Data.Entity.Core.Objects.EntityEntry.DetectChangesInForeignKeys() Unknown
EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectStateManager.DetectChangesInForeignKeys(System.Collections.Generic.IList<System.Data.Entity.Core.Objects.EntityEntry> entries) Unknown
EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectStateManager.DetectChanges() Unknown
EntityFramework.dll!System.Data.Entity.Internal.Linq.InternalSet<Wara.Data.ServerMetrics.ResourceMetric>.ActOnSet(System.Action action, System.Data.Entity.EntityState newState, object entity, string methodName) Unknown
EntityFramework.dll!System.Data.Entity.Internal.Linq.InternalSet<Wara.Data.ServerMetrics.ResourceMetric>.Add(object entity) Unknown
EntityFramework.dll!System.Data.Entity.DbSet<Wara.Data.ServerMetrics.ResourceMetric>.Add(Wara.Data.ServerMetrics.ResourceMetric entity) Unknown
> Wara.Web.Api.dll!Wara.Web.Api.Tasks.SaveMetricsTask.Do() Line 41 C#
Wara.Web.Api.dll!Wara.Web.Api.Tasks.BaseServerTask.Update(System.Threading.CancellationToken ct) Line 38 C#
Wara.Web.Api.dll!Wara.Web.Api.Setup.StartTasks.AnonymousMethod__57() Line 45 C#
mscorlib.dll!System.Threading.Tasks.Task<System.Threading.Tasks.Task<bool>>.InnerInvoke() Unknown
mscorlib.dll!System.Threading.Tasks.Task.Execute() Unknown
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown
mscorlib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot) Unknown
mscorlib.dll!System.Threading.Tasks.Task.ExecuteEntry(bool bPreventDoubleExecution) Unknown
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() Unknown
[Native to Managed Transition]

Closed Unassigned: Inconsistent behaviour with Parent-Children Relations [2809]

$
0
0
The following model has inconsistent behaviour when queried via LINQ with entities:

public class Test
{
public Test()
{
Children = new List<Test>();
}

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

public string Name { get; set; }

[ForeignKey(nameof(ParentId))]
public ICollection<Test> Children { get; set; }

public int? ParentId { get; set; }
[ForeignKey(nameof(ParentId))]
public Test Parent { get; set; }

[NotMapped]
public string Path
{
//get { return "Test"; }
get { return Parent != null ? Parent.Path + '.' + Name : Name; }
}
}
Given a simple Context like this:

public class MyContext : DbContext
{
public DbSet<Test> Tests { get; set; }
}
And then adding some data to it (in my case, like this):

Test t = new Test()
{
Text = "Child",
};
Test p = new Test()
{
Text = "Parent",
Children = new List<Test>() { t }
};
t.Parent = p;
ctx.Tests.Add(p);
ctx.SaveChanges();
And then restarting the application (so the Query/Object-Cache is cleared) and then querying like so:

foreach (Test test in ctx.Tests.Where(x => x.Text == "Child" && x.Parent != null))
{
Console.WriteLine("Is the parent null?: " + (test.Parent == null).ToString());
}
Outputs "true" for the added "Child" object.

However, querying like so:

Console.WriteLine("=== ALL ELEMENTS ===");
foreach (Test test in ctx.Tests)
{
Console.WriteLine("Found t with path " + test.Path);
}
Console.WriteLine("=== FILTERED ELEMENTS ===");
foreach (Test test in ctx.Tests.Where(x => x.Text == "Child" && x.Parent != null))
{
Console.WriteLine("Is the parent null?: " + (test.Parent == null).ToString());
}
Outputs "false" for the added "Child" object.

I tried this on a MySql Database, with both the Devart MySql Provider, and Oracles MySql Provider, and got the same behaviour on both, which leads me to think this is an issue with EntityFramework.
Note that test.ParentId is set to its correct value, just the property test.Parent does not get populated unless you first load the parent objects into the cache (ie, the caching mechanism causes a change in behaviour of population).

I find this behaviour really odd, I'm not sure if this is a bug, but it is very weird that the cache has effects like that.

Best Regards
Comments: Hey, This is by design. Here is some info to explain what is happening. When you iterate of the results of a query (i.e. your for loop) EF incrementally streams the results back from the database as each result is consumed (i.e. each iteration of the for loop pulls the next result back). As each result is “materialized” (i.e. the results are copied into an instance of the entity and registered with the context) then EF will see if there are any existing entities registered with the context that participate in relationships with the new entity. If there are, then it will “fix-up” those relationships (i.e. populating the navigation properties). In the scenario where the navigation property is null, the first iteration pulls in the child entity and the navigation property is null because the parent has not yet being brought back from the database. The second time through the for loop pulls in the parent entity, at which point the navigation property of the child is populated (“fixed-up” as we call it). In the scenario where you do a ToList(), this forces all the results into memory, which means both parent and child come back and the navigation is fixed-up. Then you iterate over the in-memory data in the list, so the navigation is populated when you iterate. If you want the navigations populated as you iterate, you can use eager loading (the Include method) to specify that you want the navigations populated. ``` foreach(Test test in ctx.Tests.Include(t => t.Parent)) ``` ~Rowan

Created Unassigned: VS2015 - Code Breaks with EF install and Migration [2813]

$
0
0
Hi!,

__What__:
I just "Add-migration" my EF end... again: I can't compile! (5 times this past week!).

__When__:
adding code first EF (in this case, the others non EF classes get mixed-up), when working with migration. Not looked further for other ways to trigger the issue...

__How__:
All using statements goes under the class definition, for all classes in the project, as:
```
namespace GYSSELS.ForexDB.DataAccess.EconomicCalendar
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;

[Table("ECONOMIC_CALENDAR.NewsHeaders")]
public partial class NewsHeader
{
[Key()]
public int NewsHeaderID { get; set; }

```

Created Unassigned: In EF6, when using TPT inheritance mapping and querying for base class properties only, JOINs for all derived classes are included in the query if at least one child collection of the base class is included [2814]

$
0
0
I have three classes:
```C#
public class EntityBase
{
public Guid Id { get; set; }

[MaxLength(50)]
public string Name { get; set; }

public List<Tag> Tags { get; set; }
}

[Table("DerivedEntities1")]
public class DerivedEntity1 : EntityBase
{
[MaxLength(50)]
public string Text { get; set; }
}

[Table("DerviedEntities2")]
public class DerivedEntity2 : EntityBase
{
public int Score { get; set; }
}
```

If I query for base entities and project only plain properties (Name, for example) - everything is fine, derived classes are not joined to the query, since no information is needed from them

```C#
var entities = dataContext.Entities
.Select(e => new { Name = e.Name })
.ToList();
```
```sql
SELECT
1 AS [C1],
[Extent1].[Name] AS [Name]
FROM [dbo].[EntityHeaders] AS [Extent1]
```

However, if I need to fetch a collection for the base class, tables for all derived classes appear in the query.
```c#
var entities = dataContext.Entities
.Include(e => e.Tags)
.Select(e => new { Name = e.Name, Tags = e.Tags })
.ToList();
```
```sql
SELECT
[Project1].[Id1] AS [Id],
[Project1].[Id2] AS [Id1],
[Project1].[Id] AS [Id2],
[Project1].[C1] AS [C1],
[Project1].[Name] AS [Name],
[Project1].[C2] AS [C2],
[Project1].[Id3] AS [Id3],
[Project1].[Value] AS [Value],
[Project1].[EntityBase_Id] AS [EntityBase_Id]
FROM ( SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent2].[Id] AS [Id1],
[Extent3].[Id] AS [Id2],
1 AS [C1],
[Extent4].[Id] AS [Id3],
[Extent4].[Value] AS [Value],
[Extent4].[EntityBase_Id] AS [EntityBase_Id],
CASE WHEN ([Extent4].[Id] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2]
FROM [dbo].[EntityHeaders] AS [Extent1]
LEFT OUTER JOIN [dbo].[DerivedEntities2] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Id]
LEFT OUTER JOIN [dbo].[DerivedEntities1] AS [Extent3] ON [Extent1].[Id] = [Extent3].[Id]
LEFT OUTER JOIN [dbo].[Tags] AS [Extent4] ON [Extent1].[Id] = [Extent4].[EntityBase_Id]
) AS [Project1]
ORDER BY [Project1].[Id1] ASC, [Project1].[Id2] ASC, [Project1].[Id] ASC, [Project1].[C2] ASC
```
Is there any possibility to avoid this?

Created Unassigned: EF Rollback failure : null connection [2815]

$
0
0

Hi,

I have a service that uses EF and EF.bulkInsert plugin to do some db operation. There is a failure with the rollback operation that I couldn't understand.

Here is a brief structure of the code:

public void BulkUpdate(Guid ObjectId, Object newObject)
{

using (var dbContextTransaction = this.Context.Database.BeginTransaction())
{
try
{
DbSetting.SuspendExecutionStrategy = true;
this.UpdateObjectWithBulkOperation(ObjectId, newObject, dbContextTransaction.UnderlyingTransaction);

dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
throw;
}
finally
{
DbSetting.SuspendExecutionStrategy = false;
}
}
}

Here is the error:

"faultDetail": ": InternalServerError : An internal server error occurred while processing the operation. : {
: UnknownInternalFailure : The service has encountered an unknown internal server error: System.Data.Entity.Core.EntityException: The underlying provider failed on Rollback. --->
System.ArgumentNullException: Value cannot be null.
Parameter name: connection
at System.Data.Entity.Utilities.Check.NotNull[T](T value, String parameterName)
at System.Data.Entity.Infrastructure.Interception.DbTransactionDispatcher.Rollback(DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.EntityClient.EntityTransaction.Rollback()
--- End of inner exception stack trace ---
at System.Data.Entity.Core.EntityClient.EntityTransaction.Rollback()
at .SomeDao.BulkUpdate(...)

a...

at lambda_method(Closure , Object , Object[] )

at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass12.b__8(Object instance, Object[] methodParameters)

at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

The error should that the conncetion is null when executing hte below method for rollback:

From: DbTransactionInterceptionContext.cs:
public DbTransactionInterceptionContext WithConnection(DbConnection connection)
{
Check.NotNull(connection, "connection");

var transactionInterceptionContext = TypedClone();
transactionInterceptionContext._connection = connection;

return transactionInterceptionContext;
}.

But what could cause the error?
Viewing all 9566 articles
Browse latest View live


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