EF 6 Code First, changing a Foreign Key Id with an Include on navigation property causes "A referential integrity constraint violation occurred" error

mips

I'm using Entity Framework 6.1.3 and have the scenario where I retrieve an entity with its navigation property (using Include()) and disconnect it from the context, change the foreign key Id then re-attach it to a new DbContext:

// Init the Db
using (var db = new MyContext())
{
   var theWarranty = new ProductWarranty { WarrantyName = "The Warranty" };
   var newWarranty = new ProductWarranty { WarrantyName = "New Warranty" };
   var brand = new ProductBrand { BrandName = "The Brand", DefaultWarranty = theWarranty };

   db.ProductBrands.Add(brand);
   db.ProductWarranties.Add(newWarranty);

   db.SaveChanges();
}

// Load the detached Brand
ProductBrand detachedBrand;
using (var db = new MyContext())
{
   detachedBrand = db.ProductBrands.AsNoTracking()
      .Include(b => b.DefaultWarranty)  // <<< If this line is removed the Attach works
      .First(x => x.Id == 1);
}

// Modify the Default Warranty Foreign Key
detachedBrand.DefaultWarranty = null;
detachedBrand.DefaultWarranty_Id = 2;

// Attempt to re-attach and save the changes
using (var db = new MyContext())
{
   var entity = db.Set<ProductBrand>().Attach(detachedBrand); // <<< This line throws the exception

   db.Entry(entity).State = EntityState.Modified;

   db.SaveChanges();
}

I'm getting:

A referential integrity constraint violation occurred: The property value(s) of >'ProductWarranty.Id' on one end of a relationship do not match the property >value(s) of 'ProductBrand.DefaultWarranty_Id' on the other end.

However, if I do NOT use the Include() the attach works fine.

I do need the navigation property (DefaultWarranty) in the real-world scenario, but I don't see the difference in including the navigation in a detached entity vs not loading it in a detached entity. From my experience and reading it should be the case of setting the foreign key to the new value and set the navigation property to null.

I've read through Ladislav's blog on Foreign Key vs Independent properties http://www.ladislavmrnka.com/2011/05/foreign-key-vs-independent-associations-in-ef-4/ but it doesn't quite deal with this scenario and from what I can tell I'm using foreign keys in this case.

What is happening and what is the correct way to deal with changing Foreign Keys with Included navigation properties like this scenario?

It's almost like EF hasn't "fully" detached the entity when the Include is used...which would seem odd as well.

Here is the simplified setup:

Product Brand

public partial class ProductBrand
{
    public int Id { get; set; }
    public string BrandName { get; set; }

    public Nullable<int> DefaultWarranty_Id { get; set; }
    public virtual ProductWarranty DefaultWarranty { get; set; }
}

Product Brand Map

public class ProductBrandMap : EntityTypeConfiguration<ProductBrand>
{
    public ProductBrandMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        this.Property(t => t.BrandName)
            .IsRequired()
            .HasMaxLength(40);

        // Table & Column Mappings
        this.ToTable("ProductBrands");
        this.Property(t => t.Id).HasColumnName("Id");
        this.Property(t => t.BrandName).HasColumnName("BrandName");
        this.Property(t => t.DefaultWarranty_Id).HasColumnName("DefaultWarranty_Id");

        // Relationships
        this.HasOptional(t => t.DefaultWarranty)
            .WithMany(t => t.ProductBrands)
            .HasForeignKey(d => d.DefaultWarranty_Id)
            .WillCascadeOnDelete(false);
    }
}

Product Warranty

public partial class ProductWarranty
{
    public ProductWarranty()
    {
        this.ProductBrands = new List<ProductBrand>();
    }

    public int Id { get; set; }
    public string WarrantyName { get; set; }
    public virtual ICollection<ProductBrand> ProductBrands { get; set; }
}

Product Warranty Map

public class ProductWarrantyMap : EntityTypeConfiguration<ProductWarranty>
{
    public ProductWarrantyMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        this.Property(t => t.WarrantyName)
            .IsRequired()
            .HasMaxLength(40);

        // Table & Column Mappings
        this.ToTable("ProductWarranties");
        this.Property(t => t.Id).HasColumnName("Id");
        this.Property(t => t.WarrantyName).HasColumnName("WarrantyName");
    }
}
Alireza

When ProxyCreationEnabled is enabled, even if the entities are not tracked by any context, they are somehow internally connected to each other. I mean, any changes in a FK is recorded carefully by the dynamic proxy entity to enforce referential integrity. So, simply turn off ProxyCreationEnabled:

public MyContext()
{
     this.Configuration.ProxyCreationEnabled = false;
}

But if you ask my opinion, I prefer to change entities when they are tracked and after modification I detach them.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Error when adding new entity to EF : A referential integrity constraint violation occurred

From Dev

Error when adding new entity to EF : A referential integrity constraint violation occurred

From Dev

Error:A referential integrity constraint violation occurred on db.SaveChanges() in .net?

From Dev

Referential integrity constraint violation occurred

From Dev

Referential integrity constraint violation occurred

From Java

EF Code First foreign key without navigation property

From Dev

EF-Code First navigation property foreign key in complex type

From Dev

Entity Framework : A referential integrity constraint violation occurred when I do EntityState.Modified

From Dev

How to expose Foreign Key property to existing entity having navigational property using EF6 Code First

From Dev

Renaming foreign key properties in code first EF classes causes an exception

From Dev

EF Code First Fluent API specifying the Foreign Key property

From Dev

EF Navigation Property with null foreign key

From Dev

Disable Foreign Key Constraint Code First EF

From Dev

EF Code First Foreign Key Same Table

From Dev

EF Code First foreign key with multiple keys

From Dev

EF Code First Foreign Key Relationship

From Dev

EF Code First Navigation Property to same table

From Dev

In Entity Framework code first, to map a navigation property do I also need to map the foreign key column

From Dev

entity framework, change foreign key but navigation property not changing

From Dev

EF6 Code First: Using Fluent API to declare a Foreign Key

From Dev

EF: Should I include foreign key ID's in my entities?

From Dev

EF 6 Add Where Clause To An Include With Navigation Property

From Dev

Do I need to add a foreign key Id property on mvc models code first

From Dev

EF6 Code First Entity with navigation property collection of same type - how do I tell EF what the relationship is?

From Dev

EF Code First The INSERT statement conflicted with the FOREIGN KEY constraint

From Dev

EF Code First Single foreign key to multiple parents

From Dev

EF Code First Migrations creating extra foreign key

From Dev

EF code first foreign key ignored, getting "Invalid column name"

From Dev

EF Code First The INSERT statement conflicted with the FOREIGN KEY constraint

Related Related

  1. 1

    Error when adding new entity to EF : A referential integrity constraint violation occurred

  2. 2

    Error when adding new entity to EF : A referential integrity constraint violation occurred

  3. 3

    Error:A referential integrity constraint violation occurred on db.SaveChanges() in .net?

  4. 4

    Referential integrity constraint violation occurred

  5. 5

    Referential integrity constraint violation occurred

  6. 6

    EF Code First foreign key without navigation property

  7. 7

    EF-Code First navigation property foreign key in complex type

  8. 8

    Entity Framework : A referential integrity constraint violation occurred when I do EntityState.Modified

  9. 9

    How to expose Foreign Key property to existing entity having navigational property using EF6 Code First

  10. 10

    Renaming foreign key properties in code first EF classes causes an exception

  11. 11

    EF Code First Fluent API specifying the Foreign Key property

  12. 12

    EF Navigation Property with null foreign key

  13. 13

    Disable Foreign Key Constraint Code First EF

  14. 14

    EF Code First Foreign Key Same Table

  15. 15

    EF Code First foreign key with multiple keys

  16. 16

    EF Code First Foreign Key Relationship

  17. 17

    EF Code First Navigation Property to same table

  18. 18

    In Entity Framework code first, to map a navigation property do I also need to map the foreign key column

  19. 19

    entity framework, change foreign key but navigation property not changing

  20. 20

    EF6 Code First: Using Fluent API to declare a Foreign Key

  21. 21

    EF: Should I include foreign key ID's in my entities?

  22. 22

    EF 6 Add Where Clause To An Include With Navigation Property

  23. 23

    Do I need to add a foreign key Id property on mvc models code first

  24. 24

    EF6 Code First Entity with navigation property collection of same type - how do I tell EF what the relationship is?

  25. 25

    EF Code First The INSERT statement conflicted with the FOREIGN KEY constraint

  26. 26

    EF Code First Single foreign key to multiple parents

  27. 27

    EF Code First Migrations creating extra foreign key

  28. 28

    EF code first foreign key ignored, getting "Invalid column name"

  29. 29

    EF Code First The INSERT statement conflicted with the FOREIGN KEY constraint

HotTag

Archive