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

Commented Unassigned: EF5 - Delete doing Not Allowed SetNull [1768]

0
0
Hello there,
I think i encountered a huge bug.

I was trying to do: delete an instance of an context by marked it as Delete, and, if it return this error:
The DELETE statement conflicted with the REFERENCE constraint
I secondly i mark it as EntityState.Unchanged, and count the Navigation Properties to show the user, how many references that instance has and where they are like this:
Example: veicleBrandinstance.VEICLES.Count
veicleBrandinstance.BRANDMODELS.Count

The problem is, the second time i try to delete that instance, the model automatically sets in the DB the VEICLES and BRANDMODELS reference to NULL and DELETES the reference allowing the model delete the instance of veicleBrandinstance. ___I didn't program the Set null , the model does that himself.___ It only happens if the foreing keys propertyes in VEICLES and BRANDMODELS are ALLOW NULL.

Other Problem is doing the same process but the VEICLES and BRANDMODELS foreign keys to BRAND are NOT NULL i can only make the count the first time i try to delete. The second time i try to delete doing the same process above:
1- mark as deleted
2 - save changes
3 - Check the error
4 - if error like above mark as unchanged
5 - count the properties
this time the count returns zero to all the properties.

Solution:
if i don't count the properties, this wrong behaviour of setnull does not happen. Simple as that.
Maybe counting the properties makes some other stuff in the background and does that.

To reproduce the error follow those steps:
1- mark as deleted (instance referenced ellsewere)
2 - save changes
3 - Check the error
4 - if error like above mark as unchanged
5 - count all the properties
6 - Expected result - Succsess
7- Do the same process again
8 - result: deletes the instance and deletes all referenced propertyes
9 - try again the above steps with no count of properties.

Please let me know if something does not make sense.

Thanks.


Comments: Hi Skiptpawa. Since I haven't heard back from you in a while, I'll close this bug as no repro. If this is still an issue for you, please to provide a small _test_ code to reproduce this issue.

Closed Unassigned: EF5 - Delete doing Not Allowed SetNull [1768]

0
0
Hello there,
I think i encountered a huge bug.

I was trying to do: delete an instance of an context by marked it as Delete, and, if it return this error:
The DELETE statement conflicted with the REFERENCE constraint
I secondly i mark it as EntityState.Unchanged, and count the Navigation Properties to show the user, how many references that instance has and where they are like this:
Example: veicleBrandinstance.VEICLES.Count
veicleBrandinstance.BRANDMODELS.Count

The problem is, the second time i try to delete that instance, the model automatically sets in the DB the VEICLES and BRANDMODELS reference to NULL and DELETES the reference allowing the model delete the instance of veicleBrandinstance. ___I didn't program the Set null , the model does that himself.___ It only happens if the foreing keys propertyes in VEICLES and BRANDMODELS are ALLOW NULL.

Other Problem is doing the same process but the VEICLES and BRANDMODELS foreign keys to BRAND are NOT NULL i can only make the count the first time i try to delete. The second time i try to delete doing the same process above:
1- mark as deleted
2 - save changes
3 - Check the error
4 - if error like above mark as unchanged
5 - count the properties
this time the count returns zero to all the properties.

Solution:
if i don't count the properties, this wrong behaviour of setnull does not happen. Simple as that.
Maybe counting the properties makes some other stuff in the background and does that.

To reproduce the error follow those steps:
1- mark as deleted (instance referenced ellsewere)
2 - save changes
3 - Check the error
4 - if error like above mark as unchanged
5 - count all the properties
6 - Expected result - Succsess
7- Do the same process again
8 - result: deletes the instance and deletes all referenced propertyes
9 - try again the above steps with no count of properties.

Please let me know if something does not make sense.

Thanks.


Comments: Couldn't repro with the supplied information.

Edited Issue: EF 6 wants to alter all DateTimeOffset columns [1850]

0
0
After upgrading to EF6, it complained of pending changes and created this migration

public override void Up()
{
AlterColumn("dbo.Contents", "DeleteDateTime", c => c.DateTimeOffset(precision: 7));
}

public override void Down()
{
AlterColumn("dbo.Contents", "DeleteDateTime", c => c.DateTimeOffset());
}

The generated alter statements are the same going up or down, as the default precision is already 7. Can you make EF not generate the migration?

Edited Unassigned: Bad performance in DbContext when using ctr [1848]

0
0
Consider this DbContext with POCO:

```
Public Class FutureEntities
Inherits DbContext

Public Sub New()

End Sub
Public Sub New()
MyBase.New(CONNECTIONSTRING)
End Sub
Public Property Customers As DbSet(Of Kund)
End Class
```
If I initalize this class with
```
Dim Context As New FutureEntities(Connectionstring)
Context.Customers.ToList()
```
it takes about 20 seconds to complete compared with:

```
Dim Context As New FutureEntities()
Context.Customers.ToList()
```

which finishes in less than 2 seconds.

Why this gigantic difference?

Edited Issue: Race condition in InitializeMappingViewCacheFactory [1843]

0
0
The race condition occurs in the Func passed to _contextTypesWithViewCacheInitialized.GetOrAdd, when setting itemCollection.MappingViewCacheFactory.

Edited Issue: Code First: ToTable doesn't always parse table name with schema [1842]

0
0
The single string overloads of ToTable should accept dotted names of the form <schema_name>.<table_name>. However, the following versions do not allow the dotted form:
C:\Dev\entityframework\src\EntityFramework\ModelConfiguration\Configuration\Mapping\EntityMappingConfiguration`.cs(278): public void ToTable(string tableName)
C:\Dev\entityframework\src\EntityFramework\ModelConfiguration\Configuration\Properties\Navigation\WithX\ManyToManyAssociationMappingConfiguration.cs(50): public ManyToManyAssociationMappingConfiguration ToTable(string tableName)
C:\Dev\entityframework\src\EntityFramework\ModelConfiguration\Configuration\Types\EntityTypeConfiguration.cs(290): public void ToTable(string tableName)



Created Unassigned: Exception combining two DbCollectionEntry.Query() calls [1851]

0
0
I get Unhandled Exception: System.ArgumentException: A parameter named 'EntityKeyValue1' already exists in the parameter collection. Parameter names must be unique in the parameter collection.
Parameter name: item
at System.Data.Entity.Core.Objects.ObjectParameterCollection.Add(ObjectParameter item)
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__a()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()

when combining two queries built from db.Entry(e).Collection(e => e.e2s).Query()

This happens both in EF5 and EF6.

Here's a complete repro:

class Author
{
public int ID { get; set; }
}
class Post
{
public int ID { get; set; }
public ICollection<Author> Authors { get; set; }
public ICollection<Comment> Comments { get; set; }
}
class Comment
{
public int ID { get; set; }
public Post Post { get; set; }
public ICollection<Author> Authors { get; set; }
}
class Context : DbContext
{
public DbSet<Post> Posts { get; set; }

static void Main()
{
using (Context db1 = new Context())
{
if (!db1.Posts.Any(p => p.ID == 1))
{
db1.Posts.Add(new Post { ID = 1, });
db1.SaveChanges();
}
}
using (Context db = new Context())
{
Post post = db.Posts.Find(1);
List<Author> authors = db.Entry(post).Collection(p => p.Authors).Query()
.Concat(db.Entry(post).Collection(p => p.Comments).Query().SelectMany(c => c.Authors))
.ToList();
}
}
}

Edited Unassigned: Exception combining two DbCollectionEntry.Query() calls [1851]

0
0
I get

Unhandled Exception: System.ArgumentException: A parameter named 'EntityKeyValue1' already exists in the parameter collection. Parameter names must be unique in the parameter collection.
Parameter name: item
at System.Data.Entity.Core.Objects.ObjectParameterCollection.Add(ObjectParameter item)
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__a()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()

when combining two queries built from db.Entry(e).Collection(e => e.e2s).Query()

This happens both in EF5 and EF6.

Here's a complete repro:

class Author
{
public int ID { get; set; }
}
class Post
{
public int ID { get; set; }
public ICollection<Author> Authors { get; set; }
public ICollection<Comment> Comments { get; set; }
}
class Comment
{
public int ID { get; set; }
public Post Post { get; set; }
public ICollection<Author> Authors { get; set; }
}
class Context : DbContext
{
public DbSet<Post> Posts { get; set; }

static void Main()
{
using (Context db1 = new Context())
{
if (!db1.Posts.Any(p => p.ID == 1))
{
db1.Posts.Add(new Post { ID = 1, });
db1.SaveChanges();
}
}
using (Context db = new Context())
{
Post post = db.Posts.Find(1);
List<Author> authors = db.Entry(post).Collection(p => p.Authors).Query()
.Concat(db.Entry(post).Collection(p => p.Comments).Query().SelectMany(c => c.Authors))
.ToList();
}
}
}

Source code checked in, #c81a3ecd80d4f98520375e837e5315f02b6e5e2e

0
0
2008 strikes back... (1832: Structural annotations not working after changeset 00a41e1493) The code for reading in custom annotations can handle XML attributes by using the attribute value string. However, it can also handle XML elements in some cases in which case the LINQ to XML XElement is placed in the EDM property. This was broken because we were attempting to cast the element to a string which results in null rather than an exception, and hence the EDM property value was null. The fix is to handle XElements as they were before without the cast or any serialization support.

Edited Issue: Structural annotations not working after changeset 00a41e1493 [1832]

0
0
Apparently changeset [00a41e1493](https://entityframework.codeplex.com/SourceControl/changeset/00a41e149341b310ccfa74a2b907079e77df484f) (Allow 'Code First' annotations to flow through the EDMX. This is required for the index attribute) introduced a functional regression.

In one of our tests we had structural annotations on the CSDL:
```
<EntityType Name="People">
<Key>
<PropertyRef Name="objectid" />
</Key>
<Property Name="objectid" Type="Int32" Nullable="false" />
<RowLevelSecurity xmlns="SystemAnnotations">
<Function Name="CheckForIdentity" xmlns="" />
</RowLevelSecurity>
</EntityType>
```
However, when reviewing the metadata properties for this entity type, the value of this annotation is an empty string.
```
XElement rowLevelSecurity = (XElement)(entityType.MetadataProperties["SystemAnnotations:RowLevelSecurity"].Value);
```
Before the changeset was commited this code returned a non-empty string and the text would be casted to an XElement. However, after the changeset this line returns an empty string and causes a System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Xml.Linq.XElement'.

Commented Issue: Structural annotations not working after changeset 00a41e1493 [1832]

0
0
Apparently changeset [00a41e1493](https://entityframework.codeplex.com/SourceControl/changeset/00a41e149341b310ccfa74a2b907079e77df484f) (Allow 'Code First' annotations to flow through the EDMX. This is required for the index attribute) introduced a functional regression.

In one of our tests we had structural annotations on the CSDL:
```
<EntityType Name="People">
<Key>
<PropertyRef Name="objectid" />
</Key>
<Property Name="objectid" Type="Int32" Nullable="false" />
<RowLevelSecurity xmlns="SystemAnnotations">
<Function Name="CheckForIdentity" xmlns="" />
</RowLevelSecurity>
</EntityType>
```
However, when reviewing the metadata properties for this entity type, the value of this annotation is an empty string.
```
XElement rowLevelSecurity = (XElement)(entityType.MetadataProperties["SystemAnnotations:RowLevelSecurity"].Value);
```
Before the changeset was commited this code returned a non-empty string and the text would be casted to an XElement. However, after the changeset this line returns an empty string and causes a System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Xml.Linq.XElement'.
Comments: Fixed in c81a3ecd80d4 2008 strikes back... (1832: Structural annotations not working after changeset 00a41e1493) The code for reading in custom annotations can handle XML attributes by using the attribute value string. However, it can also handle XML elements in some cases in which case the LINQ to XML XElement is placed in the EDM property. This was broken because we were attempting to cast the element to a string which results in null rather than an exception, and hence the EDM property value was null. The fix is to handle XElements as they were before without the cast or any serialization support.

New Post: How to connect MySql database with Entity framework model

New Post: Testing with async queries doesn't work

0
0
@tugberk and @bowser15: You might want to take a look at the code in test\EntityFramework\FunctionalTests\TestDoubles in the EF git repository. In particular, MockableDbSetTests and InMemoryDbSetTests contain running examples of ToListAsync, etc.

Thanks,
Arthur

Created Unassigned: Migration for EF 6.0 wrong migration script for altering property (required->non required) for SQL CE 4 [1852]

0
0
Using Entity Framework 6.0 and SQL CE 4.0, when __removing__ attribute [Required] for model property, migration creates query as:
```
ALTER TABLE [TableName] ALTER COLUMN [Column] [nvarchar](4000)
```
instead the query should be:
```
ALTER TABLE [TableName] ALTER COLUMN [Column] [nvarchar](4000) NULL
```
in order to properly apply the change in SQL CE.

Thanks and regards

Created Unassigned: Consider adding provider-agnostic tests to checkin suite [1853]

0
0
Currently build.cmd does not run the provider agnostic test suite, which means that these tests are usually not run before checkin or by contributors. We should consider including it.

Created Feature: ModelNamespaceConvention: Make ctor public [1854]

0
0
We should make this public so that customers have a way to override the default EDM conceptual namespace.

Created Task: [Doc] Write topic about using NGEN with EF [1855]

0
0
Consider:
- Motivation
- Bitness
- Providers
- Verification

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");
});
}
}
}

Commented Issue: Supporting Azure Federated SQL Database: Cannot Not Have Transaction Automatically Wrapped Around Database.ExecuteSqlCommand(commandText) [984]

0
0
Hi there

As a heads up...

For a while now we've successfully been using EF 5.0 with an Azure Federated SQL Database on a greenfield project (not production ready).

In order to do so, the first command that needs to be run is the "USE FEDERATION" statement and then subsequent commands on the same open connection.

This is relatively trivial to do:

```
private static void ExecuteCommand(this System.Data.Entity.DbContext ctx, string commandText)
{
var conn = ((IObjectContextAdapter) ctx).ObjectContext.Connection;
conn.Open();
ctx.Database.ExecuteSqlCommand(commandText);
}

```

In the above example, the 'commandText' being passed in is "USE FEDERATION ROOT WITH RESET" via an extension method and then a lamda expression is used on the DbContext object to get the desired result. This has been working well.

I decided to dump in EF 6.0 Alpha 3 and have a play with the new built-in support for transient faults. Oh dear...

With no code change we are suddenly getting an error from SQL Database:
.

> System.Data.SqlClient.SqlException: "USE FEDERATION ROOT statement not allowed within multi-statement transaction."

.

It appears as though EF 6 is automatically wrapping a transaction around the "ExecuteSqlCommand()".

We've tried a couple of different ways to turn off transactions. Neither works:

```
private static void ExecuteCommand(this System.Data.Entity.DbContext ctx, string commandText)
{
var conn = ((IObjectContextAdapter) ctx).ObjectContext.Connection;
conn.Open();
ctx.Database.UseTransaction(null);
ctx.Database.ExecuteSqlCommand(commandText);
}

```

```
private void SetFederationScope()
{
using (new TransactionScope(TransactionScopeOption.Suppress))
{
Context.UseFederationRoot();
}
}

```

Whilst I have your attention, of course it would be great to get first class support for federated databases such as something like but I'm not holding my breath:

```
[FederatedEntity(FederationKey = "Id")]
public class UserProfile
{
public int Id { get; set; }
public string DisplayName { get; set; }
public string EmailAddress { get; set; }
public DateTime? DOB { get; set; }
}

[NonFederatedEntity]
public class Region
{
public int Id { get; set; }
public string Name { get; set; }
}

```

In the least we need a way to turn off transactions in this scenario. Also, I remember reading something a few weeks back about EF 6 DbContext now supporting the use of an already open connection? Wondering if it's possible to open the connection and run the federation statement and then pass the connection to DbConntext...? Hmmmm..... I might play a little more... That could have merit. :)
Comments: hi, try using using (var ctx = new UsersContext()) { string federationCmdText = @"USE FEDERATION tenant_federation(id = 1) WITH RESET, FILTERING=ON"; if (ctx.Database.Connection.State != ConnectionState.Open) ctx.Database.Connection.Open(); ctx.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction,federationCmdText); } it works!!!

Commented Unassigned: Migration for EF 6.0 wrong migration script for altering property (required->non required) for SQL CE 4 [1852]

0
0
Using Entity Framework 6.0 and SQL CE 4.0, when __removing__ attribute [Required] for model property, migration creates query as:
```
ALTER TABLE [TableName] ALTER COLUMN [Column] [nvarchar](4000)
```
instead the query should be:
```
ALTER TABLE [TableName] ALTER COLUMN [Column] [nvarchar](4000) NULL
```
in order to properly apply the change in SQL CE.

Thanks and regards
Comments: The ALTER TABLE statements should always specify NULL or NOT NULL. This applies to the SQL Server Migration code as well. Do not count on any defaults.
Viewing all 10318 articles
Browse latest View live




Latest Images