如何配置从一个表(帐户)到两个表的一对多关系评论和发布
public class Account
{
public int AccountID { get; set; }
[Required(ErrorMessage = "Please enter a username")]
[Display(Name = "Username")]
public string Username { get; set; }
public string userid { get; set; }
[Required(ErrorMessage = "Please enter the password")]
[Display(Name = "Password")]
public string Password { get; set; }
public ICollection<Post> Posts { get; set; }
public ICollection<Comment> Comments { get; set; }
}
public class Post
{
public int PostId { get; set; }
[Required]
public string Heading { get; set; }
[Required]
public string PostText { get; set; }
public virtual Account Account {get;set;}
public ICollection<Comment> Comments { get; set; }
}
public class Post
{
public int PostId { get; set; }
[Required]
public string Heading { get; set; }
[Required]
public string PostText { get; set; }
public virtual Account Account {get;set;}
public ICollection<Comment> Comments { get; set; }
}
以下是我流利的api
modelBuilder.Entity<BusinessObjects.Account>().HasMany(a => a.Posts).WithRequired().Map(m => m.MapKey("AccountId"));
modelBuilder.Entity<BusinessObjects.Account>().HasMany(a => a.Comments).WithRequired().Map(m => m.MapKey("AccountId"));
modelBuilder.Entity<BusinessObjects.Post>().HasMany(p => p.Comments).WithRequired().Map(m => m.MapKey("Postid"));
以下是我得到的错误:
引入FOREIGN KEY约束 表'帖子'上的'FK_dbo.Posts_dbo.Accounts_AccountId'可能会导致 循环或多个级联路径。指定ON DELETE NO ACTION或ON 更新无操作,或修改其他FOREIGN KEY约束。不能 创建约束
我想我的流利api帐户 - &gt;帖子可能不正确,有人可以提出解决方案吗?
答案 0 :(得分:0)
您配置它的方式,所有关联都是必需的,这意味着:
因此,如果您删除帐户,它有多个路径:
这会产生不一致,因为SQL Sever在您删除帐户时并不知道该怎么做。
要解决此问题,您应该考虑将WithRequired()
替换为WithOptional()
,如果这对您有意义,然后重新尝试。
例如,考虑:
modelBuilder.Entity<BusinessObjects.Account>().HasMany(a => a.Posts).WithOptional().Map(m => m.MapKey("AccountId"));
modelBuilder.Entity<BusinessObjects.Account>().HasMany(a => a.Comments).WithOptional().Map(m => m.MapKey("AccountId"));
modelBuilder.Entity<BusinessObjects.Post>().HasMany(p => p.Comments).WithRequired().Map(m => m.MapKey("Postid"));
或者,您可以使用.WillCascadeOnDelete(false)
禁用级联删除。