-2

I have this in my Article class:

    public int GalleryID { get; set; }
    public virtual Gallery Gallery { get; set; }

and this is my gallery class:

public class Gallery
{

    public int GalleryId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Photo> Photos { get; set; }
}

when I delete gallery by this in repository:

    public virtual void Delete(int id)
    {
        T entity = dbset.Find(id);
        dbset.Remove(entity);
        dataContext.SaveChanges();
    }

I deleted article too but that isn´t what I want. I want to keep article (just maybe set galleryId to 0 a and gallery to null. Thanks

Eranga
  • 32,181
  • 5
  • 97
  • 96
Libor Zapletal
  • 13,752
  • 20
  • 95
  • 182

1 Answers1

1

In your artical make the foreign key nullable

public int? GalleryID { get; set; }

On delete of the gallery, you need to clear its article collection

public void DeleteGallery(int id)
{
    var entity = dataContext.Galleries
                .Include(e => e.Articles)  // include your child object collection
                .First(e => e.Id == id);

    dataContext.Galleries.Articles.Clear();  // this removes the reference to the parent
    dataContext.Galleries.Remove(entity);

    dataContext.SaveChanges();
}

see here EF 4.1 RC: Weird Cascade Delete

Community
  • 1
  • 1
Anthony Johnston
  • 9,405
  • 4
  • 46
  • 57