简体   繁体   中英

How to delete related fields using Entity Framework

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM