EF 保存更改突然停止工作
我的 EFv4 POCO 上下文中的 SaveChanges() 突然停止工作。它发出错误“无法将 NULL 值插入表 Clients 的列 'postalcode'”
Client
实体包含对 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() 失败。我已经彻底检查了文档实例、客户端引用和客户端的邮政编码引用,所有值都在那里(这也证明了延迟加载已到位并且正在工作),但保存没有发生。
寻找我可能错过的想法。
SaveChanges() on my EFv4 POCO context suddenly stopped working. It issues an error "Cannot insert NULL value into column 'postalcode' of table Clients"
Client
entity contains a reference to PostCode
(properties postalcode
, postname
) entity.
PostCode reference is not null and so aren't it's properties. My Client
entity is referenced from the Document
entity.
Here's the code
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();
}
The thing is, AddObject()
works but SaveChanges() fails. I've inspected the Document instance, Client reference and Client's PostCode reference all over and through, all the values are there (which also proves that lazyloading is in place and working) but save doesn't happen.
Looking for ideas what could I've missed..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,当您运行 SaveChanges 时,您会收到错误,因为此时它尝试写入数据库。在此之前,它只是存在于记忆中。
错误是邮政编码不允许为空。
我的猜测是,在模型的早期版本中,允许空值。所以有一些记录没有邮政编码。
或者,当您检索客户端时,不会检索邮政编码。
在这两种情况下,结果都是您尝试保存值为 null 的邮政编码。
Firstly, you get the error when you run SaveChanges because that is when it tries to write to the database. Before then it is just in memory.
The error is that postalcode does not allow nulls.
My guess is that in a previous version of the model nulls were allowed. So there are some records without postal codes.
Alternatively, when you retrieve the client the postalcodes are not being retrieved.
In both cases the result is that you are trying to save a postalcode with value null.