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

Edited Issue: DetectChanges() throws "An item with the same key has already been added." exception after setting a complex type property [1278]

$
0
0
Hi,

In Beta 1 the DbContext.ChangeTracker.DetectChanges() throws "An item with the same key has already been added." exception after setting a complex type property.

See the following code which reproduces the issue. The context.ChangeTracker.DetectChanges() line is the one to look for.

It would be great if it is looked at as soon as possible as it is a blocking issue for me.

Thanks

Regards

Iouri


using System;
using System.Linq;

namespace EF6b1.ComplexProperty.Bug
{
public class ComplexType
{
public virtual int? Value1 { get; set; }
public virtual int? Value2 { get; set; }
}

public class Entity
{
public virtual Guid Id { get; set; }
public virtual ComplexType ComplexProperty { get; set; }
}

public class DbContext : System.Data.Entity.DbContext
{
public DbContext(string connectionString) : base(connectionString) { }
public virtual System.Data.Entity.IDbSet<Entity> Entities { get; set; }
}


class Program
{
static DbContext CreateDbContext()
{
return new DbContext(@"Data Source=(local)\sql2012;Initial Catalog=EF6b1.ChangeTrackingBug;Integrated Security=True;MultipleActiveResultSets=True");
}
static void Main(string[] args)
{
try
{
using (var context = CreateDbContext())
{
var entity = context.Entities.Create();
context.Entities.Add(entity);
entity.Id = Guid.NewGuid();

//(IS) at the moment EF requires the complex type proeprties to be explicitly set to non-null values - I dont think it's right
entity.ComplexProperty = new ComplexType();

context.SaveChanges();
}

using (var context = CreateDbContext())
{
var entity = context.Entities.Take(1).First();

entity.ComplexProperty = new ComplexType();

//(IS) this will fail with "An item with the same key has already been added." exception originating in EntityEntry.ExpandComplexTypeAndAddvalues()
context.ChangeTracker.DetectChanges();
}

Console.WriteLine("Finished with no errors.");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

Console.WriteLine("Press any key to exit...");
Console.ReadKey(true);
}
}
}


Viewing all articles
Browse latest Browse all 10318

Trending Articles