EntityFramework可选1到1或0级联删除

时间:2014-03-06 14:06:28

标签: c# entity-framework

我无法正确设置此设置。鉴于以下类别:

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; }
    ...
}

查看一些示例,似乎配置Item类的以下行应该起作用:

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类,我对于为了工作而应该配置哪种方式感到有些困惑。

我正在寻找的是当一个项目被删除时,相应的结果也会被删除。

1 个答案:

答案 0 :(得分: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; }
}

或者在Fluent中:

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