none
Reference constraint error deleting derived type having collection navigation property RRS feed

  • Question

  • I get a The DELETE statement conflicted with the REFERENCE constraint error trying to delete an object that contains a list of other objects and derives from an other type that is mapped to a separate table.

    Here are my types:

    public class Base
    {
        public int Id { get; set; }
    }
    
    public class Main : Base
    {
        public virtual IList<ListItem> ListItems { get; set; }
    }
    
    public class ListItem
    {
        public int Id { get; set; }
    
        public int MainId { get; set; }
        public virtual Main Main { get; set; }
    }
    

    configuration:

    public DbSet<Base> Bases { get; set; }
    public DbSet<Main> Mains { get; set; }
    public DbSet<ListItem> ListItems { get; set; }
    
    modelBuilder.Entity<Base>().ToTable("SomeTable");
    modelBuilder.Entity<Main>().HasKey(x => x.Id)
                   .HasMany(x => x.ListItems)
                   .WithRequired(x => x.Main)
                   .WillCascadeOnDelete();
    

    The way I delete Main:

    context.Entry(context.Main.First()).State = EntityState.Deleted;
    context.SaveChanges();
    

    I don't get any error if Base class is not mapped to a table. This is extremely weird. What am I doing wrong here? I tried overriding the Id property of the Base type, I even tried moving the Id property to the Main type and removing it from the Base altogether, but no luck.


    • Edited by ewzer Tuesday, November 8, 2016 6:55 AM
    Thursday, October 20, 2016 11:11 AM

All replies

  • Hi ewzer,

    Based on your description and code snippet, As we know, Entity Framework relies on every entity having a key value that it uses for tracking entities. From your code, I could not find any key on model named Main. I retrieve a error like this:

    Please modify your models like this:

    public class Main : Base
    {
        public virtual IList<ListItem> ListItems { get; set; }
    }

    Or

    public class Main {

    public int Id { get; set; } public virtual IList<ListItem> ListItems { get; set; } }

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, October 21, 2016 5:43 AM
    Moderator
  • Hi, Cole Wu,

    I apologize, there was a mistake in the code that I typed in. My Main class does derive from the Base (I'll fix that in my original post), and I still get the error.

    However, I noticed that in your code, both the base and derived classes contain ListItems navigation property. Is that intentional?


    • Edited by ewzer Tuesday, November 8, 2016 6:56 AM
    Tuesday, November 8, 2016 6:54 AM