Error deleting a table row splitted on multiple entities

前端 未结 6 1017
耶瑟儿~
耶瑟儿~ 2021-01-06 05:18

I want to delete a table row that is split on two entities.

If I try to delete the main entity, I get an error if before I don\'t load the related other entity using

6条回答
  •  清歌不尽
    2021-01-06 05:53

    The best way to do this is by using a stub entity: an entity object that's only got an Id value:

    var product = context.Products.First();
    var photo = new ProductPhoto { ProductId = product.ProductId }; // Stub
    context.Entry(photo).State = System.Data.Entity.EntityState.Deleted;
    context.Products.Remove(product);
    context.SaveChanges();
    

    If you know a Product's Id you can even delete both the Product and its ProductPhoto by only creating two stubs.

提交回复
热议问题