簡體   English   中英

實體框架不會從數據庫生成所有表

[英]Entity Framework doesn't generate all tables from database

這是我數據庫中的圖表:

在此處輸入圖片說明

但是當我使用實體框架時,就像這樣:

在此處輸入圖片說明

它沒有表名ListSuiteQuestion但在QuestionSuite類中有2個新屬性:

在此處輸入圖片說明

ListSuiteQuestion由sql自動創建,因為在sql我們沒有所謂的many to many relationship (m:n)而sql創建了另一個表以實現m:n關系,其中鍵包含兩個關系表的主鍵也是兩個關系表的名稱組合的名稱。 在您的實體框架內,通過另一個表訪問每個表,您就可以訪問該表,因此無需通過實體框架對其進行定義。 但是,如果您打算自定義字段或將字段添加到第三個表,則可以將其手動構建到代碼中,然后顯示它的實體框架,盡管這不是必需的。

如果要在代碼中手動創建它,請執行以下操作:

 public class Suite
    {
        //another property
        public int IdSuite { get; set; }
        public virtual ICollection<SuitQuestions> Questions { get; set; }
    }
    public class Question
    {
        //another property
        public int IdQuestion { get; set; }
        public virtual ICollection<SuitQuestions> Suites { get; set; }
    }
    public class SuiteQuestions
    {
        public Suite Suite { get; set; }
        public int IdSuite { get; set; }
        public  Question Question { get; set; }
        public int IdQuestion { get; set; }

        //add custome property if you need

    }

並配置它。

這是正確的。 一個問題有一個套房列表,而一個套房有一個問題列表。 如果您這樣做:

        var suite = context.Suites.Find(5);
        var question = context.Questions.Find(30);
        suite.Questions.Add(question);
        // And update this suite object here;

您將在ListSuiteQuestion表中看到一個新記錄,其中IdSuite = 5且IdQuestion =30。不需要創建類ListSuiteQuestion。 但是,如果您確實要創建類,則必須將ID作為主鍵添加到Table ListSuiteQuestion中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM