【发布时间】:2010-02-16 19:58:12
【问题描述】:
我有两个表,报价和代理。 Quote 有一个名为 AgentID 的列,它是 Agent 中的外键。
在 VS 中将表格添加到我的模型时,Quote 类引用了 Agent。
当尝试添加新报价时,我创建了一个新的报价实体并像这样设置代理:
entity.Agent = (from x in entities.AgentEntities
where x.AgentID == quote.AgentID select x).FirstOrDefault();
就在调用 SaveChanges 之前,我检查了对象并看到所有值都已设置。 Agent 对象设置了它的所有值。我什至检查了 EntityKey 属性并设置了它。
尽管存在这些值,但我收到此错误:
Cannot insert the value NULL into column 'AgentID', table 'Database.dbo.Quote';
column does not allow nulls. INSERT fails.
我不知道还要检查什么,也许有办法查看 SQL?
编辑: 我在我的应用程序中使用存储库模式。我在我的应用程序中使用 PONO,然后创建新的实体对象。当我保存新报价时,我调用此方法:
public override void CreateQuote(Quote quoteToCreate)
{
var entity = ConvertQuoteToQuoteEntity(quoteToCreate);
entities.AddToQuoteEntities(entity);
entities.SaveChanges(); //Error is thrown here
}
private QuoteEntity ConvertQuoteToQuoteEntity(Quote quote)
{
var entity = new QuoteEntity();
if (quote != null)
{
entity.QuoteID = quote.QuoteID;
entity.DiscoveryMethod = quote.DiscoveryMethod;
entity.CompletedDateTimeStamp = quote.CompletedDateTimeStamp;
entity.CommisionAmount = quote.CommisionAmount;
entity.QuoteKey = quote.QuoteKey;
entity.SelectedOption = quote.SelectedOption;
entity.SentDateTimeStamp = quote.SentDateTimeStamp;
entity.CustomerName = quote.CustomerName;
entity.CustomerEmail = quote.CustomerEmail;
entity.CustomerPrimaryPhone = quote.CustomerPrimaryPhone;
entity.CustomerAlternatePhone = quote.CustomerAlternatePhone;
entity.Agent = (from x in entities.AgentEntities where x.AgentID == quote.AgentID select x).First<AgentEntity>();
}
return entity; //Everything looks good here (Agent is fully populated)
}
这里有点奇怪。我能够看到生成的 SQL,它对我来说看起来很奇怪:
insert [dbo].[Quote]([QuoteKey], [CommisionAmount], [QuoteRequestID], [DiscoveryMethod], [SelectedOption], [CreatedDateTimeStamp], [SentDateTimeStamp], [CompletedDateTimeStamp], [CustomerName], [CustomerEmail], [CustomerPrimaryPhone], [CustomerAlternatePhone])
values (@0, null, null, @1, null, @2, null, null, @3, @4, @5, @6)
select [QuoteID], [AgentID]
from [dbo].[Quote]
where @@ROWCOUNT > 0 and [QuoteID] = scope_identity()
【问题讨论】:
-
你能显示更多的代码吗?您可以使用 SQL Profiler 查看 SQL。
-
基于
INSERT,它根本没有设置Quote.AgentId字段,因此是NULL。由于您说entity.Agent不是NULL,这意味着可能是代理属性映射错误,或者EF 认为您没有更改它。前者似乎更有可能。我建议仔细检查映射。 -
好吧,我决定“放弃”并切换到 Linq 2 SQL。根据我的经验,EF 是复杂的,或者只是没有准备好。或者有一些基本的东西我就是不明白。
-
通常,当人们难以让 EF 正常工作时,他们会编写太多代码——同时使用多个 ObjectContexts,不必要地摆弄映射等等。我最好的建议是从非常简单的东西开始,从那里开始工作和构建。
-
更新:我已经升级到 .NET 4 并且一切正常 - 我没有遇到上述问题。
标签: .net entity-framework