简体   繁体   中英

Entity Framework Cascade delete doesn't work

For some reason I'm not able to use Cascade Delete with Entity Framework. I'm trying to automatically delete a row of "Players" when I delete one of "HighScoreListEntry", but even if the SQL Code looks fine it does only delete the row in the HighScoreListEntry table.

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 Code

    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);

I know the method name isn't the best but that's not the problem

    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;
    }

It should not work the way you expected.

When you remove HighScoreListEntry , no Player entity is removed as it is parent one. If you were removing an Player all HighScoreListEntry entities belonging to the removed player would be deleted as well.

See related question for reference - How do I use cascade delete with SQL Server?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM