2012-04-17 67 views
-2

我在我的文章類有這個不是其他項目:刪除項目,但與此相關的

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

,這是我的畫廊類:

public class Gallery 
{ 

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

,當我這個在刪除圖庫repository:

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

我也刪除了文章,但那不是我想要的。我想保留的文章(僅僅是可能設置galleryId 0和畫廊爲null。謝謝

+1

請問你的問題涉及到ASP.NET MVC3?它看起來更像你是問如何使用一些ORM(其中的方式你不是S在你的問題pepe)。是EF還是什麼?請使用適當的標籤。 – 2012-04-17 07:50:07

+0

我很抱歉,是的,它是EF。 – 2012-04-17 08:01:33

回答

1

在你ARTICAL使外鍵可爲空

public int? GalleryID { get; set; } 

。刪除該畫廊的,你需要明確它的文章收集

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(); 
} 

看到這裏EF 4.1 RC: Weird Cascade Delete

+0

這可能有幫助,但現在我有這個問題:「主鍵值不能被刪除,因爲對這個鍵的引用仍然存在[外鍵約束名稱= FK_Articles_Galleries_GalleryID]」 – 2012-04-17 08:01:10

+0

你使用的代碼第一流利的API?你怎麼指定FK? – 2012-04-17 08:05:56

+0

現在,類中的代碼就足夠了。你能幫助我與我shoudl添加到'protected覆蓋無效OnModelCreating(DbModelBuilder模型構建器)「? – 2012-04-17 08:17:10