Kod Entity Framework (EF) Pierwsze kasowanie kaskadowe dla relacji jeden-do-zero-lub-jeden
Podążając za sekcją „Modelowanie pierwszego kodu”Kurs Pluralsight „Pierwsze kroki z Entity Framework 5” Julie Lerman, Stworzyłem dwie klasy POCO za pomocąjeden do zera lub jeden relacja: rodzic (użytkownik) i anopcjonalny dziecko (UserDetail).
Schemat modelu danych użytkownika i użytkownika (kliknij, aby wyświetlić).
Zauważ na schemacie, żewłaściwość UserId jest kluczem podstawowym i kluczem obcym dla UserDetail.
Odpowiedni kod:
public class User
{
//...
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
/* Has a 1:0..1 relationship with UserDetail */
public virtual UserDetail UserDetail { get; set; }
//...
}
public class UserDetail
{
//...
/* Has a 0..1:1 relationship with User */
public virtual User User { get; set; }
[Key, ForeignKey("User")]
public int UserId { get; set; }
//...
}
public class EFDbContext : DbContext
{
public DbSet<User> Users { get; set; }
//public DbSet<UserDetail> UserDetails { get; set; } /* Explicit declaration not necessary. Context is aware of UserDetail entity due to 0..1:1 relationship with User */
public EFDbContext()
{
Configuration.ProxyCreationEnabled = true;
Configuration.LazyLoadingEnabled = true;
}
}
public class UserRepository : IUserRepository
{
private EFDbContext _context = new EFDbContext();
public void Delete(User entity)
{
entity = _context.Users.Find(entity.UserId);
//...
_context.Users.Remove(entity);
_context.SaveChanges();
//...
}
}
Gdy wywoływana jest metoda Delete () w klasie UserRepository, nie usuwa ona rekordu użytkownika w bazie danych, ponieważ klucz obcy w UserDetail nie ma włączonego kasowania.
Instrukcja DELETE jest w konflikcie z ograniczeniem REFERENCE „FK_dbo.UserDetail_dbo.User_UserId”.
Jak włączyć kasowanie kaskadowerelacje jeden-do-zero-lub-jeden za pomocą kodu Entity Framework Najpierw (aby usunąć użytkownika automatycznie usuwa UserDetail)?