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

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 問題。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 兩種方式操作,彈性更高。
SaveChanges。Include("NavigationProperty") 急切載入,或啟用延遲載入(注意 Context 生命週期)。