繁体   English   中英

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

[英]EntityFramework Optional 1 to 1 or 0 Cascade Delete

我无法正确设置此设置。 给定以下类别:

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类,并且我对应该使用哪种方法进行配置感到困惑。

我要寻找的是删除项目时相应的结果也被删除。

实体框架不支持唯一约束(唯一外键)。 您必须使用共享的主键来获得这种关系。

尝试这个:

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

或流利的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM