Im trying to avoid cascading deleting by changing the Id of the delete item to null for all "Cats" that have the CatLitter Id. can someone tell me what i need to do. this is what i come up with so far im pretty sure im somewhere in the right direction.
Problem: when i delete CatLitter - All Cats that have CatLitterId also gets deleted.
public ActionResult CatLittersDelete(int Id)
{
CatLitter ni = db.CatLitters.Find(Id);
foreach (var item in ni.Cats.Where(m => m.CatLitterId == Id))
{
item.CatLitterId = null;
db.Entry(item).State = EntityState.Modified;
}
db.CatLitters.Remove(ni);
db.SaveChanges();
return RedirectToAction("CatPropCreate");
}
Model:
public class Cat
{
public int Id { get; set; }
public string Name { get; set; }
public int? CatLitterId { get; set; }
public virtual CatLitter CatLitters { get; set; }
Using Entity Framework Code First.
So im trying this now from what u guys have given me:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Cat>()
.HasOptional<CatLitter>(s => s.CatLitters)
.WithMany()
.WillCascadeOnDelete(false);
}
but im getting this when i try update db.
One or more validation errors were detected during model generation:
CatProject.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType. CatProject.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType. IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined. IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
WillCascadeOnDelete(false)
, but is cascaded delete off in the database? I bet it isn't. The exception is aboutIdentityUserRole
, so it's not related to your question. – Gert Arnold