【问题标题】:Operation failed: can't delete an entity from database操作失败:无法从数据库中删除实体
【发布时间】:2013-08-19 12:51:23
【问题描述】:

我有这些方法类:

public class Links
{
    [Key]
    public int LID { get; set; }
    public string Link { get; set; }
    public string Type { get; set; }
    public string Filename { get; set; }
    public virtual int RessourceId { get; set; }
}

public class Ressource
{
    [Key]
    public int RessourceId { get; set; }
    public string TitreR { get; set; }
    public string Desc { get; set; }
    //public int Position { get; set; }
    public int Rating { get; set; }
    public string Tags { get; set; }
    public virtual int SectionId { get; set; }
    public virtual int UserId { get; set; }
    public virtual ICollection<Links> Links { get; set; }

}

public class Section
{
    [Key]
    public int SectionId { get; set; }
    public string Titre { get; set; }
    public virtual ICollection<Tags> Tags { get; set; }

    public virtual ICollection<Ressource> Ressources { get; set; }
    //public Section() { this.Tag=new List<string>(); }
}

当我想删除资源时,我遇到了这个错误:

操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新的关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。

错误行:

_db.Entry(R).State = EntityState.Deleted;
_db.SaveChanges();    // error line

PS:在我将 Filename 属性添加到 Links 类之前它正在工作......知道如何解决它吗?谢谢

【问题讨论】:

    标签: entity-framework foreign-key-relationship


    【解决方案1】:

    使外键可以为空(即将其类型从int 更改为int?):

    public virtual int? RessourceId { get; set; }
    

    这意味着您可以在没有资源的情况下获得链接。

    【讨论】:

    • 谢谢,它工作了,但我没明白,为什么在我添加这个属性之前它工作得很好? (文件名)
    猜你喜欢
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多