3

I have an object like this :

public class MyObject
{
    [Key]
    public int Id { get; set; }

    public string ExternalNumber { get; set; }


    public virtual InternalProperties InProperties { get; set; }

    public virtual ICollection<AdditionalPrice> PriceHistory{ get; set; }
}

And InternalProperties class :

public class InternalProperties
{
    [Key]
    public int Id { get; set; }
    public string  Field1{get; set;}
}

And PriceHistory :

public class AdditionalPrice
{
    [Key]
    public int Id { get; set; }
    public double? Price { get; set; }
}

And my context look like this :

public class myContext : DbContext
{
        static myContext ()
        {
            Database.SetInitializer<myContext >(null);
        }

        public myContext ()
            : base("myCtx")
        {
        }

        public DbSet<MyObject> Objects{ get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
           modelBuilder.Entity<myObject>().HasOptional(m => m.InProperties );
           modelBuilder.Entity<myObject>().HasMany(m => m.PriceHistory);
        }

}

Finally I'm trying to delete myObjects like this :

            using (var _sdb = new MyContext())
            {
                _sdb.Configuration.AutoDetectChangesEnabled = false;
                var myList = _sdb.Objects.Where(m => m.Id > 5).OrderBy(c => c.Id).ToList();
                foreach(var obj in myList)
                {
                 _sdb.Objects.Remove(obj)
                }

            }
_sdb.SaveChanges();

I'm getting this exception at SaveChanges():

{"An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details."}

And Inner Exception says :

{"The DELETE statement conflicted with the REFERENCE constraint \"FK_dbo.AdditionalPrice_dbo.MyObject_MyObject_Id\". The conflict occurred in database \"myobject\", table \"dbo.AdditionalPrice\", column 'myObject_Id'.\r\nThe statement has been terminated."}

The exceptions are pretty explanatory but I don't know how to delete these objects safely. I appreciate any help. Thanks in advance.

3
  • the message is clear, there's foreign key, and you should delete foreign records first Commented Mar 10, 2017 at 7:02
  • @LeiYang Yes I get that too, but I couldn't figure out how to do it. Commented Mar 10, 2017 at 7:03
  • @LeiYang I can't reach and delete that Price history. Commented Mar 10, 2017 at 7:04

1 Answer 1

2

I think that you need something like this:

var pricesToBeDeleted = _sdb.AdditionalPrices.Where(ap=>ap.MyObjectId == obj.Id);
_sdb.AdditionalPrices.Remove(pricesToBeDeleted);
_sdb.Objects.Remove(obj)

The AdditionalPrices would be of type DbSet<AdditionalPrice>. You should add the following line in your myContext class:

public DbSet<AdditionalPrice> Objects{ get; set; }

Regarding the AdditionalPrice class, I don't see the foreign key to MyObject. I think that you miss something there. I mean that you might have something like the following:

public class AdditionalPrice
{
    [Key]
    public int Id { get; set; }
    public double? Price { get; set; }
    public int MyObjectId { get; set; }
}

where MyObjectId is the foreign key. If the name MyObjectId isn't the same with the corresponding column name you should change, in order they match one another.

Sign up to request clarification or add additional context in comments.

4 Comments

As you can see my context doesn't have AdditionalPrices. Should I add that into context first?
Yes, this is what I was writing a few seconds before :)
Thanks for the answer, but the AdditionalPrice class doesn't have a foreign key. Is it still safe to delete using Id?
@jason You are welcome. If I am not wrong the Id is the primary key of the record, not the foreign key to the MyObject table. That being said I think that this is not correct. Furthermore, since the error message you get refers to a foreign key and the AdditionPrice represents a record of the corresponding table shouldn't we have there a property like MyObjectId, which would have been the foreign key?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.