实体框架级联删除不起作用

时间:2016-12-13 17:51:21

标签: c# sql entity-framework

由于某些原因,我无法使用Cascade Delete with Entity Framework。我试图自动删除一排玩家"当我删除其中一个" HighScoreListEntry"时,即使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;
    }

1 个答案:

答案 0 :(得分:0)

它不应该按照你预期的方式工作。

删除HighScoreListEntry时,不会删除Player实体,因为它是父实体。如果您要删除Player属于已删除播放器的所有HighScoreListEntry个实体,也会被删除。

请参阅相关问题以供参考 - How do I use cascade delete with SQL Server?