Pergunta

I have a Question Entity. My entity contains a CreatedFrom of type Question that contains a reference to the question it was created from. So a self reference.

Now I use the CreatedFrom to update the original question as long as it's around. But the user can remove the original question, leaving my question "orphaned". This however is perfectly okay as it's the design of the system.

Now I added this line to my DbContext:

modelBuilder.Entity<Question>().HasOptional(x => x.CreatedFrom);

But it still refuses to let me delete the "parent" saying relation is in the way.

What I want is to be able to delete the parent, and when I do the CreatedFrom should be nulled on any Question that has the CreatedFrom set to the ID of the now deleted question.

Foi útil?

Solução

You must load the child questions into the context. If you delete the parent EF should set the reference CreatedFrom for all attached children to null and save this as an UPDATE to the database:

using (var context = new MyContext())
{
    var parentQuestion = context.Questions
        .SingleOrDefault(q => q.Id == someId);

    if (parentQuestion != null)
    {
        context.Questions
            .Where(q => q.CreatedFrom.Id == someId)
            .Load();

        context.Questions.Remove(parentQuestion);
        context.SaveChanges();
    }
}

If you have a ChildQuestions collection property in Question you can simplify this by adding Include(q => q.ChildQuestions) to the query for the parentQuestion and remove the query that loads the children explicitly.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top