2014-09-23 43 views
0

我如何去從一個表(帳戶)配置一個一對多的關係,兩個表評論和張貼之一,從一個表中的許多多個表

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")); 

以下是錯誤我得到:

引進國外KEY約束 「FK_dbo.Posts_dbo.Accounts_表'帖子'上的AccountId'可能導致 週期或多個級聯路徑。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束。不能 創建約束

我想我的流利api帳戶 - >發佈可能不正確,任何人都可以提出解決方案嗎?

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 – 2014-09-23 22:53:04

回答

0

您配置的方式,所有的協會都是必須的,意思是說:

  • 如果您刪除帳戶,您級聯刪除相關帖子。
  • 如果您刪除某個賬戶,則會級聯刪除所有相關的註釋。
  • 如果您刪除了一篇文章,則會級聯刪除所有評論。

因此,如果您刪除帳戶,它具有多條路徑:

  • 它可以刪除所有相關的帖子,然後將所有相關評論
  • 它可以刪除所有相關評論

這會產生不一致性,因爲SQL Sever在您刪除帳戶時並不確切知道該怎麼做。

要解決這個問題,您應該考慮用WithOptional()替換一些WithRequired(),如果這對您有意義,然後重試。

例如,考慮:

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)

相關問題