2014-03-06 35 views
0

我無法正確設置此設置。鑑於以下類:EntityFramework可選1至1或0級聯刪除

public class Item 
{ 
    [Key, Column(Order = 0)] 
    public long UserId { get; set; } 

    [Key, Column(Order = 1)] 
    public long ToDoId { get; set; } 

    public long? ResultId { get; set; } 

    [ForeignKey("ResultId")] 
    public virtual Result Result { get; set; } 
    ... 
} 

public class Result 
{ 
    [Key] 
    public int Id { get; set; } 
    ... 
} 

看着它出現一些例子,下面一行配置項類應該工作:

HasOptional(x => x.Result).WithOptionalDependent().WillCascadeOnDelete(true); 

但這只是得到一個驗證錯誤:

Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'. 

這應如何配置。一些例子是配置Item類,一些例子是配置Result類,並且我對於應該配置哪種方法來工作有些困惑。

我在找的是一個項目被刪除時,相應的結果也被刪除。

+0

試試這個:

public class Item { [Key, Column(Order = 0)] public long UserId { get; set; } [Key, Column(Order = 1)] public long ToDoId { get; set; } public virtual Result Result { get; set; } } public class Result { public int Id { get; set; } [Required] public Item Item { get; set; } } 

還是以流利。屬性ResultId應該是兩個表中的主鍵。其他方式將是1到* – Uriil

回答

0

實體框架不支持唯一約束(唯一外鍵)。您必須使用共享主鍵來獲得這種關係。如果你想擁有1對1或0的關係

modelBuilder.Entity<Item>() 
    .HasOptional(f => f.Result) 
    .WithRequired(f => f.Item) 
    .WillCascadeOnDelete(true);