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

Created Unassigned: Use Fully Qualified Names [1844]

$
0
0
Version: EF6

Issue:
When generating the DBContext class, the context fails to compile if the table name conincides with a System name, for example "Environment".

The fix would be to modify the tt template to always use the fully qualified name when generating the context class.
An added suggestion would be to default to using fully qualified type names in ALL generated code.

![Image](http://example.com/logo.jpg)

Edited Unassigned: Use Fully Qualified Names [1844]

$
0
0
Version: EF6

Issue:
When generating the DBContext class, the context fails to compile if the table name conincides with a System name, for example "Environment".

The fix would be to modify the tt template to always use the fully qualified name when generating the context class.
An added suggestion would be to default to using fully qualified type names in ALL generated code.

![Image](https://www.codeplex.com/Download/AttachmentDownload.ashx?ProjectName=entityframework&WorkItemId=1844&FileAttachmentId=759489)

Edited Unassigned: Use Fully Qualified Names [1844]

$
0
0
Version: EF6

Issue:
When generating the DBContext class, the code fails to compile if the table name coincides with a System name, for example "Environment".

The fix would be to modify the tt template to always use the fully qualified name when generating the context class.
An added suggestion would be to default to using fully qualified type names in ALL generated code.

![Image](https://www.codeplex.com/Download/AttachmentDownload.ashx?ProjectName=entityframework&WorkItemId=1844&FileAttachmentId=759489)

Commented Issue: “The given key was not present in the dictionary.” when adding Association to Entities - all mapped to Views [1777]

$
0
0
When mapping entities and associations exclusively to SQL views, you get the a KeyNotFoundException. This does not occur when working with SQL tables.

See this question on StackOverflow for more information and a sample project:
[http://stackoverflow.com/questions/19631162/the-given-key-was-not-present-in-the-dictionary-when-adding-association-to-en](http://stackoverflow.com/questions/19631162/the-given-key-was-not-present-in-the-dictionary-when-adding-association-to-en)
Comments: @patman0021: if you feel brave, overwrite the EntityFramework.dll located in %Program Files(x86)%\Microsoft Visual Studio 12.0\Common7\IDE with the one you got from nightly build (make sure to back-up the original one) and the EF designer should no longer show the error.

Commented Unassigned: Version 6.0.2-nightly-21113 DbEntityValidationException without detail [1835]

$
0
0
With Version 6.0.2-nightly-21113
Calling SaveChanges() returned DbEntityValidationException but detail not provided. see attached image

{System.Data.Entity.Validation.DbEntityValidationResult}

public override int SaveChanges()
{
try
{
base.SaveChanges();

}
catch (DbEntityValidationException)
{
throw;
}
}
Comments: Verified to exist in both EF5 and EF6+. Reproduction is exactly as rnaveh has described. However, I think this is a VS issue. The exception details are only missing in the VS Exception Snapshot Viewer (View Details… link in exception window); the details show up just fine in the Locals window when debugging.

Edited Unassigned: Version 6.0.2-nightly-21113 DbEntityValidationException without detail [1835]

$
0
0
With Version 6.0.2-nightly-21113
Calling SaveChanges() returned DbEntityValidationException but detail not provided. see attached image

{System.Data.Entity.Validation.DbEntityValidationResult}

public override int SaveChanges()
{
try
{
base.SaveChanges();

}
catch (DbEntityValidationException)
{
throw;
}
}

Commented Issue: Memory leak in case of usage an external connection [1805]

$
0
0
EF6 has a memory leak in some specific situations. Please look at following code.

```
using (var connection = new SqlConnection(connectionString))
{
connection.Open();

using (var transaction = connection.BeginTransaction())
{
// need to use a lot of small updates instead of one update, because the count of affected records is very big and MemoryOverflow exception can be thrown
for (int i = 0; i < 100; i++)
{
using (var context = new DbContext(connection, false))
{
context.Database.UseTransaction(transaction);

// some updates and inserts

context.SaveChanges();

context.Database.UseTransaction(null);
}

// there is a memory leak.
// all disposed context are stayed in the memory
// the cause of this behavior is attached event handler for the event StateChange on connection
}

transaction.Commit();
}
}

```

If DbContext is created with external connection, then such context will not be disposed, because EntityConnection attached an event handler to the StateChange event in the external connection and this handler is not detached during disposing of DbContext. Therefore GC cannot collect this instance of context.

I use following workaround for this situation.

```
private static void ContextDisposingWorkaround(DbContext context)
{
var connection = context.Database.Connection;
var objectContext = ((IObjectContextAdapter) saveContext).ObjectContext;

ReflectionHelper.RemoveEventHandlers(typeof (DbConnection), "StateChange", "_stateChangeEventHandler", connection,
objectContext.Connection);
}
```
Need to call above method before disposing of context.
Comments: I believe your fix did make it in, as the _stateChangeEventHandler is now null after the DbContext is disposed, previously this was not the case. But the EntityConnection is definately not disposed when the DbContext is. Other than my observation of memory usage, I'm basing this on the fact that certain properties on the EntityConnection (eg ConnectionString) are populated following dbContext.Dispose(), but then cleared after I make the explicit call to entityConnection.Dipose(). Unfortunately I cannot send my entire source, but I suspect that you are correct that our setups are different. The setup we're using is somewhat perculiar. We have a single DbConnection in this scenario, each time we iterate we create a new EntityConnection based on this DbConnection: var entityConnection = new EntityConnection(MetadataWorkspace, dbConnection)) then contstruct a new DbContext using the EntityConnection, eg new DbContext(entityConnection) at the end of the iteration the dbConext is disposed (as is the EntityConnection explicitly as a workaround), but the DbConnection lives on. The reason we do this is so that we can do all this using a single SqlConnection there it can be done transactionally without the need for DTC. I hope this explanation helps.

Commented Unassigned: EF5 -> EF6 Conversion: designer won't let go of EF5 [1827]

$
0
0
Using VS2012, database first. [This issue](https://entityframework.codeplex.com/workitem/806) informs me that, in addition to upgrading my nuget package to EF6, I need to install support for the new designer. After doing so, the designer still targets EF5 namespaces even if I update the model from the database.

Part (or all?) of the problem is nuget. EF6 is installed for my project, but if I select to manage nuget packages for solution, the nuget dialog reports "Some NuGet packages are missing from this solution." If I click "Restore" EF5 comes back. I tried deleting all package.config files and the entire packages directory to no avail.
Comments: Make sure to remove a reference to System.Data.Entity.dll. For existing project if you have a reference to System.Data.Entity.dll and the edmx file does not have a setting letting it know it is an EF6 model (UseLegacyProvider="False") it will treat your model as EF5. Restoring to EF5 is probably a result of entries in the package.config file. Instead of removing the existing EF5 EF.dll and adding EF6 nuget package you should use Update-Package command to upgrade from EF5 to EF6.

Commented Issue: EF5: StackOverflowException on query with a long condition list [1834]

$
0
0
I’m getting a StackOverflowException for a simple query with a very long list of fairly simple conditions of the same kind, like following:
SELECT VALUE it FROM Container.Set AS it WHERE ((it.Id = 1)) OR ((it.Id = 2)) OR ((… and so on))
In my environment, I get the exception on approx. 5000 condition elements. When reducing condition list by half (~2500 elements), the query works just fine. Replacing the condition list by a single IN condition is not an option for me.

In the stack trace, I see the same four frames repeating thousands of times:
System.Data.Entity.dll!System.Data.Common.EntitySql.SemanticAnalyzer.ConvertValueExpressionAllowUntypedNulls + 0x47 bytes
System.Data.Entity.dll!System.Data.Common.EntitySql.SemanticAnalyzer.ConvertLogicalArgs + 0x1d bytes
System.Data.Entity.dll!System.Data.Common.EntitySql.SemanticAnalyzer.CreateBuiltInExprConverter.AnonymousMethod__81 + 0xd bytes
System.Data.Entity.dll!System.Data.Common.EntitySql.SemanticAnalyzer.ConvertBuiltIn + 0x59 bytes

Apparently, there is some recursive algorithm in the Semantic Analyzer instead of a one using a loop.

This behavior makes it nearly impossible to select large amounts of filtered data.

Comments: Hello Dennis, Thanks for following up. I looked too quickly at your report the first time. I missed asking you what version of EF you were using but also the fact that you were using Entity SQL, which is not controlled by the UseCSharpNullComparisonBehavior flag at all. We will need to take a deeper look at this issue to understand what is going on and how it can be fixed. We will let you know if we have any issues reproducing it. In the meanwhile, have you had a chance to try if this repros with EF6? Thanks, Diego

Edited Issue: EF5: StackOverflowException on query with a long condition list [1834]

$
0
0
I’m getting a StackOverflowException for a simple query with a very long list of fairly simple conditions of the same kind, like following:
SELECT VALUE it FROM Container.Set AS it WHERE ((it.Id = 1)) OR ((it.Id = 2)) OR ((… and so on))
In my environment, I get the exception on approx. 5000 condition elements. When reducing condition list by half (~2500 elements), the query works just fine. Replacing the condition list by a single IN condition is not an option for me.

In the stack trace, I see the same four frames repeating thousands of times:
System.Data.Entity.dll!System.Data.Common.EntitySql.SemanticAnalyzer.ConvertValueExpressionAllowUntypedNulls + 0x47 bytes
System.Data.Entity.dll!System.Data.Common.EntitySql.SemanticAnalyzer.ConvertLogicalArgs + 0x1d bytes
System.Data.Entity.dll!System.Data.Common.EntitySql.SemanticAnalyzer.CreateBuiltInExprConverter.AnonymousMethod__81 + 0xd bytes
System.Data.Entity.dll!System.Data.Common.EntitySql.SemanticAnalyzer.ConvertBuiltIn + 0x59 bytes

Apparently, there is some recursive algorithm in the Semantic Analyzer instead of a one using a loop.

This behavior makes it nearly impossible to select large amounts of filtered data.

Created Unassigned: Model validation should fail, when HasRequired is set for optional foreign key. [1845]

$
0
0
Suppose you have these models:

```
public class A
{
public int Id { get; set; }
// other properties here
}

public class B
{
public int Id { get; set; }
// other properties here
}

public class C
{
public int Id { get; set; }
public int? AId { get; set; }
public A A { get; set; }
public int? BId { get; set; }
public B B { get; set; }
// other properties here
}

```
and C is configured this way:

```
class CConfig : EntityTypeConfiguration<C>
{
public CConfig()
{
// other properties and keys

HasRequired(_ => _.A)
.WithMany()
.HasForeignKey(_ => _.AId);
HasRequired(_ => _.B)
.WithMany()
.HasForeignKey(_ => _.BId);
}
}

```
Note, that navigation properties are configured with errors: as they're optional, `HasOptional` instead of `HasRequired` should be used.

Later, query like this:

```
context
.CEntities
.Where(c => c.A == null || c.B == null);

will produce SQL like this:
```

```
SELECT
-- here are C fields
FROM C_Table AS [Extent1]
WHERE ((1 = 0) OR (1 = 0))

```
which will return empty result set every time.

This behavior isn't obvious. Instead of generating invalid SQL, model validation should fail, when `HasRequired` is set for optional foreign key.

Edited Unassigned: Model validation should fail, when HasRequired is set for optional foreign key. [1845]

$
0
0
Suppose you have these models:

```
public class A
{
public int Id { get; set; }
// other properties here
}

public class B
{
public int Id { get; set; }
// other properties here
}

public class C
{
public int Id { get; set; }
public int? AId { get; set; }
public A A { get; set; }
public int? BId { get; set; }
public B B { get; set; }
// other properties here
}

```
and `C` is configured this way:

```
class CConfig : EntityTypeConfiguration<C>
{
public CConfig()
{
// other properties and keys

HasRequired(_ => _.A)
.WithMany()
.HasForeignKey(_ => _.AId);
HasRequired(_ => _.B)
.WithMany()
.HasForeignKey(_ => _.BId);
}
}

```
Note, that navigation properties are configured with errors: as they're optional, `HasOptional` instead of `HasRequired` should be used.

Later, query like this:

```
context
.CEntities
.Where(c => c.A == null || c.B == null);
```

will produce SQL like this:

```
SELECT
-- here are C fields
FROM C_Table AS [Extent1]
WHERE ((1 = 0) OR (1 = 0))

```
which will return empty result set every time.

This behavior isn't obvious. Instead of generating invalid SQL, model validation should fail, when `HasRequired` is set for optional foreign key.

Reviewed: EF 6.0.1 (十一月 19, 2013)

$
0
0
Rated 5 Stars (out of 5) - I like it very much

Created Unassigned: Mark pure methods with PureAttribute [1846]

$
0
0
Please consider making pure methods of ObjectQuery, DbQuery and their generic counterparts with PureAttribute. First of all it concerns all variants of Include(), since developers make oftentimes the same mistake by losing a modified query copy returned by the the method. A PureAttribute would help smart IDE Tolls like R# to issue a warning in that case.

New Post: Namespace is changed when moving EDMX file to another folder

$
0
0
This is REALLY annoying glitch (full video - http://sdrv.ms/HUi7m5). Say, I have generated some model. The file is called "TestModel.edmx". Then, I begin creating code:
namespace TestEF
{
   async private void OnGetData(object sender, RoutedEventArgs e)
   {
       using(TestEntities db = new TestEntities())
       {
           await db.T1.LoadAsync();
           dg.ItemsSource = db.T1.Local; //dg - DataGrid
       }
   }
}
All is well and good. But after some time I have decided to create folder in project named "Database" and move this EDMX file to this folder. And...error appears:

The type or namespace name 'TestEntities' could not be found (are you missing a using directive or an assembly reference?)

Whatta??? My "TestEF" namespace for T1 class has been changed to "TestEF.Database"! In other words, VS appended the folder name to namespace. And because of it I have to change the namespace in each and every source code file! What if I have 300 files where I use this namespace?

Is it cool feature or I don't understand something?

New Post: SQL Server Compact 3.5 provider for EF6

$
0
0
Hi Team, I have heard a few requests for a SQL Server Compact 3.5 provider for EF6 - how do you feel about me adding that to the codebase? (Only minor changes to the 4,0 provider are required as far as I can see)

New Post: Multiple contexts per db and automatic migration

$
0
0
In my current project I use one db for different contexts using HasDefaultSchema. All contexts have a custom initializer, that automatically migrates to the newest version using Database.CompatibleWithModel(), DbMigrator.Update() and a configuration that has AutomaticMigrationsEnabled set to true.

Two things are unclear to me:

Initial DbMigration

The first Add-Migration for each contexts contains the complete model - as expected. Accessing the contexts for the first time calls the initializer and updates the db correctly using the specified schemas. From this point on, automatic migrations are applied correctly for all contexts/schemas. Without an initial Add-Migration the migrator fails to insert any table, even if the db is empty.

The documentation says:
"However, for implementation reasons, transferring the __MigrationHistory table to a different schema can only occur using a code-based migration."

So, why does migrations refuse to automatically update an empty db without an initial DbMigration, but adds tables of an other context/schema to a db, that already contains tables of another context/schema (with an initial code-based migration)? The expected behavior was, that without any added DbMigration the complete model gets added to an empty db, where no schema transferring should be neccessary.

DbMigration discovery

Not having read the source code of ef much, it's hard to know how DbMigrations are discovered. I implemented a custom initializer to do automatic migration, because my connection string names are only known at runtime (one db per tenant).

When using DbMigrationsConfiguration<TContext> only to enable automatic migrations,the custom initializer could be simplified by just creating a generic configuration for the context at runtime, enable automatic migrations and supply it to the DbMigrator.

If I don't use a derived configuration class in the same assembly as the migrations, the initial DbMigration can not be found (in the assembly of the context) and the update fails. Is there a way to tell DbMigrator where the DbMigrations live without implementing a configuration?

Thanks in advance
mat

Edited Issue: Code First: TPC with joins from base class to Identity ApplicationUser Fails [1791]

$
0
0
I have been moving code from EF 5 to a new project using EF 6 and AspNet Identity, and got the following error when trying to enable code first migrations:
"The referenced EntitySet 'Ad' for End 'Ad' could not be found in the containing EntityContainer."

I have a TCP inheritance with a base class (just one! - not the same issue as http://entityframework.codeplex.com/workitem/981) and I have narrowed it down to joining my abstract class ("Ad") to my users ("ApplicationUser") with one-to-many navigation properties. The code works on EF 5.

Simplified (but fully reproducing) code, based on a new MVC Web Application:

using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace WebApplication1.Models
{
//You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
//Can't enble this navigation property
//public virtual ICollection<Ad> Ads { get; set; }
}
public abstract class Ad
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
public int AdID { get; set; }
public string UserId { get; set; }
public string Name { get; set; }

//Can't enble this navigation property
//public virtual ApplicationUser User { get; set; }
}
public class Boat : Ad
{
public int Width { get; set; }
public int Length { get; set; }

}
public class Equipment : Ad
{
public string Description { get; set; }
public int Price { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}

public System.Data.Entity.DbSet<WebApplication1.Models.Ad> Ads { get; set; }
public System.Data.Entity.DbSet<WebApplication1.Models.Boat> Boats { get; set; }
public System.Data.Entity.DbSet<WebApplication1.Models.Equipment> Equipment { get; set; }

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Boat>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Boats");
});
modelBuilder.Entity<Equipment>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Equipment");
});
}
}
}

Edited Issue: Perf: Revert buffering by default [1819]

$
0
0
Related to #1786 and possibly #1781, the change to buffering is being more impactful than we initially thought it would be. Testing against the provided repros yields performance degradation of 103% and 36% respectively.

We now think the best thing to do is to revert back to streaming by default. In particular:

1) Change default query execution back to streaming. But,
2) Use buffering if the current IDbExecutionStrategy retries on failure.
3) Deprecate the AsStreaming() extension method.

Edited Issue: Small bug in ExpressionConverter [1789]

$
0
0
I think there is a small bug in System.Data.Entity.Core.Objects.ELinq.ExpressionConverter method RecursivelyRewriteEqualsExpression. The code looks like this:

```
private DbExpression RecursivelyRewriteEqualsExpression(DbExpression left, DbExpression right, EqualsPattern pattern)
{
// check if either side is an initializer type
var leftType = left.ResultType.EdmType as RowType;
var rightType = left.ResultType.EdmType as RowType;
```

Shouldn't the last statement be:
```
var rightType = __right__.ResultType.EdmType as RowType;
```
Viewing all 10318 articles
Browse latest View live




Latest Images

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