首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Entity Framework 讀寫外鍵關聯實戰:導航屬性賦值與 Include 載入

     編輯:關於.NET

資料庫結構

新聞表 News 與分類表 NewsClass 之間建立外鍵關聯(News.ClassId → NewsClass.Id)。

ER 圖 EDMX 導航屬性

關鍵點:EF 將外鍵欄位隱藏,轉為導航屬性

  • News 實體不再有 ClassId 基本屬性,改為 NewsClass 導航屬性(型別 NewsClass)。
  • 寫入/讀取外鍵關係,必須透過導航屬性操作實體物件。

寫入:新增新聞並關聯分類

public bool AddNews(string title, int classId, string content, DateTime date, int hot) {
    using (var ctx = new DemosEntities()) {
        try {
            // 1. 先取得目標分類實體
            var category = ctx.NewsClass.First(c => c.Id == classId);
            // 2. 建立新聞實體,指派導航屬性
            var news = new News {
                NewsTitle = title,
                NewsContent = content,
                NewsDate = date,
                NewsHot = hot,
                NewsClass = category   // 關鍵:賦值導航屬性,EF 自動處理 FK
            };
            ctx.AddToNews(news);
            ctx.SaveChanges();
            return true;
        } catch (Exception ex) {
            Log.Error(ex);
            return false;
        }
    }
}

讀取:查詢新聞並同時載入分類資訊

public List<News> GetNewsList() {
    using (var ctx = new DemosEntities()) {
        // Include("NewsClass") 指定急切載入導航屬性
        return ctx.News.Include("NewsClass").ToList();
    }
}
  • 若省略 Include,news.NewsClass 為 null(延遲載入需開啟 Proxy 且在 Context 存活期內)。
  • Include 產生 SQL JOIN,單次查詢取回主從資料,避免 N+1 問題。

進階:EF 5/6 可同時保留 FK 屬性與導航屬性

public class News {
    public int Id { get; set; }
    public int ClassId { get; set; }           // 外鍵屬性(可選)
    public virtual NewsClass NewsClass { get; set; } // 導航屬性
}

啟用 ForeignKey Attribute 或 Fluent API 映射,即可同時以 news.ClassId = 5 或 news.NewsClass = cat 兩種方式操作,彈性更高。

總結

  1. EF Code First/Database First 預設以導航屬性代表關聯。
  2. 寫入:查詢主體實體 → 指派給導航屬性 → SaveChanges。
  3. 讀取:使用 Include("NavigationProperty") 急切載入,或啟用延遲載入(注意 Context 生命週期)。
  4. 新版 EF 可保留 FK 標量屬性,兼顧效能與物件導向便利。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved