Mam bazę danych SQL Server taką jak ta: tabela główna, tabela szczegółów, tabela szczegółów. I używam Linq i EF 4.0.
Zatem mistrz może mieć więcej szczegółów, a każdy szczegół może mieć więcej szczegółów.
Mam MASTER ID i chcę usunąć ten rekord.
Jak mogę usunąć rekord główny ze szczegółami i szczegółami szczegółowymi w un colpo solo (EF4.0)?
Odpowiedzi:
1 dla odpowiedzi № 1EF domyślnie włącza kaskadowy efekt usuwania dla wszystkich jednostek.
Następujące dane są kopiowane z tutaj.
Rozważ następujące jednostki studenckie i standardowe, które mają relację jeden do wielu.
public class Student
{
public Student() { }
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual Standard Standard { get; set; }
}
public class Standard
{
public Standard()
{
Students = new List<Student>();
}
public int StandardId { get; set; }
public string Description { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
Poniższy przykład pokazuje kaskadowy efekt usuwania między jednostkami, które mają relację jeden do wielu.
using( var ctx = new SchoolContext() ) {
var student1 = new Student() { StudentName = "James" };
var student2 = new Student() { StudentName = "Gandhi" };
var standard1 = new Standard() { StandardName = "Standard 1" };
student1.Standard = standard1;
student2.Standard = standard1;
ctx.Students.Add( student1 );
ctx.Students.Add( student2 );
//inserts students and standard1 into db
ctx.SaveChanges();
//deletes standard1 from db and also set standard_StandardId FK column in Students table to null for
// all the students that reference standard1.
ctx.Standards.Remove( standard1 );
ctx.SaveChanges();
}
W powyższym przykładzie usuwa standard1 z db, a także ustawia kolumnę standard_StandardId FK w tabeli Uczniów na null dla wszystkich rekordów, które odwołują się do standard1.
EF automatycznie usuwa powiązane rekordy w środkowej tabeli dla encji relacji wiele do wielu, jeśli jedna lub druga jednostka zostanie usunięta.
Dlatego EF domyślnie włącza kaskadowy efekt usuwania dla wszystkich jednostek.