2014-01-25 33 views
0

我有一個表格'評論',我想存儲包含日期的評論列表。這些註釋可以屬於三個不同的類,每個類都有自己的db表。 我第一次嘗試這樣做:實體框架代碼優先的許多表格的一個表格

public class Comment 
    { 
     public int CommentID { get; set; } 
     public virtual int OwnerID { get; set; } 
     public string Description { get; set; }   
    } 

但我無法弄清楚如何使用三種不同級別的使用它。

我的下一個選擇是:

public class Comment 
    { 
     public int CommentID { get; set; } 
     public virtual IAcceptComment Owner { get; set; } 
     public string Description { get; set; }   
    } 

我的接口分配給三個班,但我得到一個錯誤嘗試配置的情況下爲實體之一:(顯式轉換存在(是否缺少投))

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Event>().HasMany<Comment>(e => e.Comments).WithMany(c =>  c.Owner);    
    } 

我已經使用模型首先看EF如何生成的類,這是它做什麼?

public class Comments 
    { 

    public int Id { get; set; } 
    public string Comment { get; set; } 

    public virtual ICollection<Consultant> Consultant { get; set; } 
    public virtual ICollection<Event> Event { get; set; } 
    public virtual ICollection<Company> Company { get; set; } 

}

難道沒有辦法避免創建導航屬性嗎?你能想到任何其他近似的問題?

謝謝。

+0

你能舉個例子嗎?我的想法是試圖創建一個泛型類,如果我必須使用'comments'來完成每個類的數組,那麼它幾乎與導航屬性相同。 –

+0

抱歉誤導.ya我試過了,它仍然有導航。名單顧問和數組[class]基本上都相同既有導航,因爲,都是數據列表。 – Eldho

回答

0

我認爲你可以使用繼承在EF

Inheritance Refernece

TPT Inheritance Usage msdn

TpT Usages

這將幫助你避免導航電學性能的研究

做出這樣的查詢

 'var db = new MySchoolEntities(); 

     foreach (var department in db.Departments) 
     { 
      Console.WriteLine(); 
      Console.WriteLine("The {0} department has the following courses:", 
         department.Name); 

      Console.WriteLine(); 
      Console.WriteLine(" All courses"); 

      foreach (var course in department.Courses) 
      { 
       Console.WriteLine(" The Course Name {0}", course.Title); 
      } 

      Console.WriteLine(); 

      if (department.Courses.OfType<OnlineCourse>().Count() > 0) 
      { 
       Console.WriteLine(" Online courses are"); 
       foreach (var online in department.Courses.OfType<OnlineCourse>()) 
       { 

        Console.WriteLine("Online Course is {0} & Link : {1} ", online.Title, online.URL); 

       } 
      } 

      Console.WriteLine(); 

      Console.WriteLine(" Onsite courses are"); 

      foreach (var onsite in department.Courses.OfType<OnsiteCourse>()) 
      { 
       Console.WriteLine(" Online Course Venue : {0} ", onsite.Location); 
      } 


     } 

     Console.ReadLine(); 

希望這會讓你避免漫長的導航。

相關問題