我有一個實體的集合:的EntityFramework與現有數據庫 - 導航屬性不工作
public class Board : EntityBase
{
public ICollection<Slot> Slots { get; set; }
}
public class Slot : EntityBase
{
public ICollection<Card> Cards { get; set; }
public string Header { get; set; }
public int BoardId { get; set; }
}
public class Card : EntityBase
{
public string Description { get; set; }
public string Title { get; set; }
public int SlotId { get; set; }
}
和相應的數據庫表:
CREATE TABLE Boards
(
Id INT PRIMARY KEY,
UserId INT NOT NULL,
CONSTRAINT FK_Users_UserId FOREIGN KEY (UserId)
REFERENCES Users(Id)
)
CREATE TABLE Slots
(
Id INT PRIMARY KEY,
Header NVARCHAR(MAX),
BoardId INT NOT NULL,
CONSTRAINT FK_Slots_BoardId FOREIGN KEY (BoardId)
REFERENCES Boards(Id)
)
CREATE TABLE Cards
(
Id INT PRIMARY KEY,
Title NVARCHAR(MAX),
Description NVARCHAR(MAX),
SlotId INT NOT NULL,
CONSTRAINT FK_Cards_SlotId FOREIGN KEY (SlotId)
REFERENCES Slots(Id)
)
當試圖檢索和從實例化一個「公告板」數據庫沒有填充'Slots'屬性。看來,實體框架無法識別有外鍵約束。我的理解是,如果這些屬性不是虛擬的,它們將會被加載,如果我錯了,請糾正我。
有什麼我丟失/需要設置使導航屬性工作?
調用代碼:
Context.Boards.Find(id);
我的DbContext:
public class SampleContext : DbContext, IUnitOfWork
{
public SampleContext() : base("name=SampleApplication") { }
public void Save()
{
SaveChanges();
}
public DbSet<Board> Boards { get; set; }
public DbSet<Card> Cards { get; set; }
public DbSet<Slot> Slots { get; set; }
}
我所做的導航屬性虛擬和加載如下,這是現在的工作:
public Board GetBoard(int id)
{
var board = Context.Boards.Find(id);
Context.Entry(board)
.Collection(b => b.Slots)
.Load();
return board;
}