2015-05-29 13 views
6

(इकाई की रूपरेखा 6, .NET 4, वी.एस. 2010)इकाई की रूपरेखा 1-हैं- * और 1 से 1

मैं इस समस्या को वर्णन करने के लिए एक छोटा सा ब्लॉग प्रोजेक्ट बनाया हुआ है। यह एक ब्लॉग है जिसमें कई पद हैं लेकिन पदों में से केवल एक ही मुख्य पोस्ट के रूप में कार्य करता है।

public class Blog 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Post> PostEntities { get; set; } 

    public int? MainPostId { get; set; } 

    [ForeignKey("MainPostId")] 
    public virtual Post MainPostEntity { get; set; } // Problem here 
} 

public class Post 
{ 
    public int Id { get; set; } 
    public int BlogId { get; set; } 
    [ForeignKey("BlogId")] 
    public virtual Blog BlogEntity { get; set; } 
    public string Title { get; set; } 
} 

modelBuilder.Entity<Blog>() 
    .HasOptional(b => b.MainPostEntity) 
    .WithRequired(p => p.BlogEntity); 

static void Main(string[] args) 
{ 
    Database.SetInitializer<EFTestContext>(null); 
    EFTestContext db = new EFTestContext(); 
    Post[] posts = db.Posts.ToArray(); // Error here 
} 

यदि मैं नेविगेशन प्रॉपर्टी को हटा देता हूं public virtual Post MainPostEntity सब कुछ अपेक्षित काम करता है। हालांकि, जब मैं इसे जोड़ने के लिए, मैं:

base {System.SystemException} = {"The ForeignKeyAttribute on property 'MainPostEntity' on type 'EFTest.Blog' is not valid. The foreign key name 'MainPostId' was not found on the dependent type 'EFTest.Post'. The Name value should be a comma separated list of foreign key property names."}

अगर मैं धाराप्रवाह API कॉल निकालने के लिए, मैं {"Invalid column name 'Blog_Id'."}

मिलता है मैं [ForeignKey("MainPostId")] से [ForeignKey("Id")] मैं निम्न त्रुटि प्राप्त करने के लिए विशेषता बदली {"Invalid column name 'Blog_Id'."}

मैं क्या गलत कर रहा हूं? मैं नेविगेशन प्रॉपर्टी को ब्लॉग से मुख्य पोस्ट में कैसे सक्षम करूं?

उत्तर

2

समस्या आप कर रहे हैं कि आप एक ही दो टेबल और एफई के बीच दो रिश्ते बना रहे हैं भेद नहीं कर सकते जो संबंध नेविगेशन संपत्ति BlogEntity का हिस्सा है। धाराप्रवाह एपीआई का उपयोग करके आप स्पष्ट रूप से इसे बता सकते हैं, डेटा एनोटेशन की आवश्यकता नहीं है।

modelBuilder.Entity<Blog>().HasMany(b => b.PostEntities). 
          WithRequired(p => p.BlogEntity). 
          HasForeignKey(p => p.BlogId). 
          WillCascadeOnDelete(true); 

modelBuilder.Entity<Blog>().HasOptional(b => b.MainPostEntity). 
          WithMany(). 
          HasForeignKey(b => b.MainPostId). 
          WillCascadeOnDelete(false); 
+0

धन्यवाद, यह काम किया! – Adam

+0

आपका स्वागत है, मदद करने में खुशी हुई। – user2697817

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