views:

459

answers:

1

I am trying to create a list of LINQ to SQL objects which i will add to the datacontext and insert later. When i do call SubmitChanges() though I get an error saying the Postcode foreign key for the WeatherForecast object is null.

I appears that when List.Add() is called it doesn't do a deep copy of the dependent objects. Is there anyway to make it do a deep copy?

This is an example of what i'm trying to do.

function List<WeatherForecast> CreateForecast(Postcode postcode) 
{ 
   var forecasts = List<WeatherForecast>();

   var wf = new WeatherForecast() 
   { 
      ForecastDate = DateTime.Today
      , CurrentTemperature = (decimal)today.Attribute(XName.Get("temperature"))
   };
   wf.Postcode = postcode;

   forecasts.Add(wf); 

   ...
   Keep adding forecast objects into the list
   ...

   return forecasts;
}
A: 

List.Add doesn't make a copy at all. Assuming WeatherForecast is a reference type, you are simply storing a reference to the WeatherForecast you just created.

The problem is probably that you are using a Postcode object that hasn't been added to the database yet.