如何在Entity Framework 6中删除集合级联中的对象?

时间:2015-09-07 10:00:49

标签: sql-server entity-framework sql-server-2012

我将这两个对象作为ASP.NET MVC应用程序的一部分:

public Problem()
    {
        this.Questions = new HashSet<Question>();
    }
    public string Answer { get; set; }
    public virtual ICollection<Question> Questions { get; set; }
}

public class Question
{
    public int QuestionId { get; set; }
    public int ProblemId { get; set; }
    public string Title { get; set; }
    public virtual Problem Problem { get; set; }
}

我将此映射添加到问题:

this.HasRequired(t => t.Problem)
   .WithMany(t => t.Questions)
   .HasForeignKey(d => d.ProblemId);

现在,当我从问题对象中删除其中一个问题并保存时,它会从问题表中删除问题,但问题在问题表中保留为孤儿。

我有没有办法让它删除这个问题?

这里参考的是DDL:

CREATE TABLE [dbo].[Problem] (
    [ProblemId]       INT             IDENTITY (1, 1) NOT NULL,
    [Answer]          NVARCHAR (4000) NULL,
    CONSTRAINT [PK_Problem] PRIMARY KEY CLUSTERED ([ProblemId] ASC)
);
GO
CREATE TABLE [dbo].[Question] (
    [QuestionId]       INT              IDENTITY (1, 1) NOT NULL,
    [ProblemId]        INT              NOT NULL,
    [Title]            NVARCHAR (100)   NULL,
    [Explanation]      NVARCHAR (4000)  NULL,
    CONSTRAINT [PK_Question] PRIMARY KEY CLUSTERED ([QuestionId] ASC),
    CONSTRAINT [FK_QuestionProblem] FOREIGN KEY ([ProblemId]) REFERENCES [dbo].[Problem] ([ProblemId]),
);
GO
CREATE NONCLUSTERED INDEX [Question_ProblemId_IX]
    ON [dbo].[Question]([ProblemId] ASC);
GO

0 个答案:

没有答案