在的“代码优先模型”一节继Pluralsight“入门与实体框架5”由朱莉·勒曼当然 ,我创建了两个POCO类有一到零或一对一的关系:父(用户)和一个可选孩子(UserDetail)。
用户和UserDetail数据模型图(点击查看)。
请注意,UserID属性是一个主键和UserDetail外键的图所示。
相关的代码:
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();
//...
}
}
当UserRepository类的delete()方法被调用,它不会删除用户记录在数据库中,因为在UserDetail外键没有级联删除。
DELETE语句冲突与基准约束“FK_dbo.UserDetail_dbo.User_UserId”。
你将如何实现级联删除一到零或一对一的关系使用实体框架代码优先(以便删除用户将自动删除UserDetail)?