0
出於某種原因,我無法使用實體框架級聯刪除。當我刪除「HighScoreListEntry」之一時,我試圖自動刪除一行「Players」,但即使SQL代碼看起來不錯,它也只會刪除HighScoreListEntry表中的行。實體框架級聯刪除不起作用
public class Player
{
//Navigation Property
public List<HighScoreListEntry> HSLEs { get; set; }
//Properties
public int PlayerId { get; set; }
public String FName { get; set; }
public String LName { get; set; }
public Player(String fName, String lName)
{
FName = fName;
LName = lName;
}
public Player()
{
}
}
public class HighScoreListEntry
{
//Navigation Property
[Required]
public Player Player { get; set; }
//Foreign key
public int PlayerID { get; set; }
//Properties
[Key]
public int HSLEId { get; set; }
public TimeSpan Duration { get; set; }
public DateTime Time { get; set; }
public int Value { get; set; }
public HighScoreListEntry(Player player, TimeSpan duration, DateTime time, int value)
{
if (value < 0) throw new FormatException();
Player = player;
Duration = duration;
Time = time;
Value = value;
}
public HighScoreListEntry()
{
}
}
HighScoreListEntry DDL代碼
CREATE TABLE [dbo].[HighScoreListEntries] (
[HSLEId] INT IDENTITY (1, 1) NOT NULL,
[PlayerID] INT NOT NULL,
[Duration] TIME (7) NOT NULL,
[Time] DATETIME NOT NULL,
[Value] INT NOT NULL,
CONSTRAINT [PK_dbo.HighScoreListEntries] PRIMARY KEY CLUSTERED ([HSLEId] ASC),
CONSTRAINT [FK_dbo.HighScoreListEntries_dbo.Players_PlayerID] FOREIGN KEY ([PlayerID]) REFERENCES [dbo].[Players] ([PlayerId]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_PlayerID]
ON [dbo].[HighScoreListEntries]([PlayerID] ASC);
我知道方法名是不是最好的,但是這不是問題
public bool edit(HighScoreListEntry entryOld, HighScoreListEntry entryNew)
{
try
{
db.HSLE.Remove(entryOld);
db.HSLE.Add(entryNew);
db.SaveChanges();
} catch (Exception f)
{
Console.WriteLine(f.ToString());
return false;
}
return true;
}