【问题标题】:One to one relationship failing in entity framework code first一对一关系首先在实体框架代码中失败
【发布时间】:2011-11-08 07:40:11
【问题描述】:

我正在尝试首先建立一对一的关系 EF v4.1 代码。这是我的代码:

public class System
{
    [Key, ForeignKey("Station") ] 
    public int Id { get; set; }

    [DisplayName("Last Polled")]
    public DateTime? LastPolledOn { get; set; }

    public virtual Station Station { get; set; }
}

public class Station
{
    public int Id { get; set; }               
    public int Status { get; set; }

    public string FullName
    {
        get
        {
            return StoreNumber + " - " + StoreName;
        }
    }

    public virtual System System{ get; set; }        
}

这很好,但是当我删除 Station 时,我得到级联删除错误:

"无法删除主键值,因为对该键的引用仍然存在。[外键约束名称 = System_Station]"}"

我应该怎么做才能解决这个问题?

【问题讨论】:

    标签: c# entity-framework entity-framework-4.1 ef-code-first code-first


    【解决方案1】:

    正如错误信息告诉你的那样,Station 仍然存在外键关系,所以先使用级联删除或删除System 中的相关行。

    【讨论】:

    • 先打我一分钟..我太慢了!
    • @Phil:你不知道这种情况发生在我身上的频率有多高,因为这里有很多“快速打字机”;-)...
    • 我了解您的第二种方法,首先手动删除系统。但是如何使用级联删除?我需要在代码中进行哪些更改?谢谢chrfin。
    • @Anthony:我不是 EF 用户,所以我不能完全帮助你,但请查看以下链接:blogs.msdn.com/b/alexj/archive/2009/08/19/…
    【解决方案2】:

    System 的主键也是 Station 的外键。如果您删除 Station,您需要先删除 System。您也可以使用级联删除。

    【讨论】:

    • 嗨菲尔,我如何使用级联删除。我需要对我的代码进行哪些更改?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多