5

नष्ट नहीं कर सकते मैं इस त्रुटि:एफई - कैस्केड हटाएँ काम नहीं कर रहा, वस्तु

public class Post 
    { 
     public long Id { get; set; } 
     public string Body { get; set; }  

     public long? ParentId { get; set; } 
     public virtual Post Parent { get; set; } 
     public virtual ICollection<Post> Posts { get; set; } 

     public virtual ICollection<Comment> Comments { get; set; } 
    } 

    public class Comment 
    { 
     public long Id { get; set; } 
     public long PostId { get; set; } 
     public virtual Post Post { get; set; } 
     public string Body { get; set; } 
    } 

मेरी हटाने विधि:

public void Delete(long id) 
    { 
     var p = context.Set<Post>().Get(id); 
     if(p == null) throw new MyEx("this post doesn't exist"); 
     if (p.Posts.Count > 0) throw new MyEx("this post has children and it cannot be deleted"); 
     context.Set<Post>().Remove(p); 
     context.SaveChanges(); 
    } 

System.Data.SqlClient.SqlException The DELETE statement conflicted with the REFERENCE constraint "FK_comments_postId__164452B1". The conflict occurred in database "awe", table "dbo.comments", column 'postId'. The statement has been terminated.

मैं इस संरचना है मेरा डीबीकॉन्टेक्स्ट:

public class Db : DbContext 
{ 
    public DbSet<Post> Posts { get; set; } 
    public DbSet<Comment> Comments { get; set; } 
} 

उत्तर

20

ऐसा लगता है कि आप जिस पोस्ट को हटाने की कोशिश कर रहे हैं वह बाल टिप्पणियां है।

इकाई फ्रेमवर्क डेटाबेस में एक डिलीट को कैस्केड करने की ज़िम्मेदारी नहीं लेगा - यह उम्मीद करता है कि आप आरडीबीएमएस में विदेशी कुंजी संबंधों पर एक कैस्केडिंग डिलीट सेट करके इसे प्राप्त करेंगे।

कहा करने के बाद यह, यदि आप इकाई की रूपरेखा में एक माता पिता इकाई को हटाते हैं, यह किसी भी बच्चे संस्थाओं जो वर्तमान DbContext में लोड किया गया है के लिए हटाने बयान जारी करने के लिए प्रयास करेगा, लेकिन यह किसी भी बच्चे संस्थाओं अभी तक नहीं है जो प्रारंभ नहीं होगा लोड किया गया है। यह आरडीबीएमएस को विदेशी कुंजी बाधा उल्लंघन अपवादों को फेंकने का कारण बन सकता है यदि एक कैस्केडिंग डिलीट निर्दिष्ट नहीं किया गया है, जैसा कि आप देख रहे हैं। एंटीटी फ्रेमवर्क, see this blog post में कैस्केड "काम" को कैसे हटाता है, इस बारे में अधिक जानकारी के लिए।

संबंधित मुद्दे