【问题标题】:EF Saving changes suddenly stopped workingEF保存更改突然停止工作
【发布时间】:2011-06-18 19:17:28
【问题描述】:

我的 EFv4 POCO 上下文中的 SaveChanges() 突然停止工作。它发出错误"Cannot insert NULL value into column 'postalcode' of table Clients"

Client 实体包含对PostCode(属性postalcodepostname)实体的引用。 PostCode 引用不为空,它的属性也不是。我的Client 实体引用自Document 实体。

这是代码

    public void Add(Document instance)
    {
        // Firm reference
        instance.Firm =
         (from f in _ctx.Firms
            where f.firm_id.Equals(AppState.FirmId)
            select f).First();

        // Client reference (lazy loading is in place and works)
        if (instance.client_id != null)
            instance.Client = (from c in _ctx.Clients
                                                 where c.client_id.Equals(instance.client_id)
                                                 select c).First();

        instance.document_id = Guid.NewGuid();
        _ctx.Documents.AddObject(instance);
        _ctx.Documents.SaveChanges();
    }

问题是,AddObject() 有效,但 SaveChanges() 失败。我已经检查了 Document 实例、客户端引用和客户端的 PostCode 引用,所有的值都在那里(这也证明延迟加载已经到位并且工作)但没有保存。

寻找我可能错过的想法..

【问题讨论】:

  • postalcodePostCode 真的是一回事吗?
  • PostCode 是一个包含 postalcode 和 postname 属性的实体。这也是我们在数据库中存储邮政编码的方式。
  • 正确,但错误消息显示它是Client 上的一列。这意味着postcode 是复杂类型的一部分。但你的问题暗示它不是。没有看到数据库和映射很难说更多,但它看起来很可疑。
  • 是的,客户端上有邮政编码导航属性,客户端上有邮政编码(FK 列)。与最近对 EF 的更改有关,您可以在其中选择导航属性和 FK 属性。
  • EditorFor 和模型绑定存在问题,我还没有完全弄清楚。我将关闭它,并可能打开一个关于 EditorFor 的新文件。

标签: entity-framework entity-framework-4 efpocoadapter


【解决方案1】:

首先,您在运行 SaveChanges 时会遇到错误,因为那是它尝试写入数据库的时候。在此之前它只是在内存中。

错误是邮政编码不允许空值。

我的猜测是在模型的先前版本中允许使用空值。所以有些记录没有邮政编码。

或者,当您检索客户端时,不会检索到邮政编码。

在这两种情况下,结果都是您尝试保存值为 null 的邮政编码。

【讨论】:

    猜你喜欢
    • 2017-08-22
    • 2021-02-01
    • 2016-12-29
    • 2018-05-09
    • 2015-12-07
    • 2015-08-23
    • 2014-02-05
    • 2013-09-06
    相关资源
    最近更新 更多