I have two tables, Quote and Agent. Quote has a column called AgentID that is a foreign key in Agent.
When adding the tables to my model in the VS the Quote class has a reference to Agent.
When attempting to add a new quote I create a new quote entity and set the Agent like this:
entity.Agent = (from x in entities.AgentEntities
where x.AgentID == quote.AgentID select x).FirstOrDefault();
Right before SaveChanges is called I examine the object and see that all of the values are set. The Agent object has all of its values set. I even checked the EntityKey property and it is set.
Despite the values being there I am getting this error:
Cannot insert the value NULL into column 'AgentID', table 'Database.dbo.Quote';
column does not allow nulls. INSERT fails.
I am not sure what else to check, perhaps there is a way to view the SQL?
EDIT: I am using the repository pattern in my application. I use PONO's in my application then create new entity objects. When I save a new quote I call this method:
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)
}
Here is something odd. I was able to see the SQL generated and it looks strange to me:
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()