我有以下类和EF约定创建表 - 一切都很好。现在我想在ToDoList上配置级联删除(这样当我删除ToDoList时,所有ToDoItems和UserToDoLists也会被自动删除)。我必须重新指定EF约定能够检测哪些才能设置WillCascadeOnDelete?如何在流畅的API中指定此关系?
public class ToDoList
{
public int Id { get; set; }
public string Description { get; set; }
public virtual ICollection<ToDoItem> ToDoItems { get; set; }
public virtual ICollection<UserToDoList> UserToDoLists { get; set; }
}
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
: base()
{
}
public virtual ICollection<UserToDoList> UserToDoLists { get; set; }
}
// a todolist can have many users and a user can have many todolist
// junction table will have addition fields
public class UserToDoList
{
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual int ToDoListId { get; set; }
public virtual ToDoList ToDoList { get; set; }
// additional fields
public bool IsOwner { get; set; }
public int Ordinal { get; set; }
public bool AllowEdit { get; set; }
}
public class UserToDoListConfig : EntityTypeConfiguration<UserToDoList>
{
public UserToDoListConfig()
{
HasKey(ut => new { ut.UserId, ut.ToDoListId });
}
}
public class ToDoListConfig : EntityTypeConfiguration<ToDoList>
{
public ToDoListConfig()
{
Property(t => t.Description).IsRequired().HasMaxLength(50);
HasMany(t =>t.UserToDoLists).??
}
}
答案 0 :(得分:0)
这是从ToDoList
到您的联结表UserToDoList
的简单的一对多关系,所以您只需设置这样的映射
HasMany(m => m.UserToDoLists)
.WithRequired(m => m.ToDoList)
.HasForeignKey(m => m.ToDoListId);
和EF将自动处理您的级联删除,因为在联结表端需要ToDoList
。