I'm at wits end here. The problem is I'm trying to create a new entity in the database, with a db generated identity property, in LINQ to SQL and then create another entity associated with the first one. I'm guessing the problem is that LINQ to SQL cannot insert the second entity without the id from the first entity, which won't be known until the database generates it.
Has anyone else had this problem... if so how did you resolve it? I know I could call SubmitChanges
between the creation of the first and the second entity, but this would break the transactional integrity of the program.
Here's a concrete example:
[Table(Name = "Searches")]
public class Search
{
// Db Generated Key
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public Int32 SearchID { get; set; }
// Each search can have multiple search parameters
private EntitySet<SearchParam> searchParams;
[Association(Storage = "searchParams", ThisKey = "SearchID", OtherKey = "SearchID")]
public EntitySet<SearchParam> SearchParams
{
get
{
return searchParams;
}
set
{
searchParams.Assign(value);
}
}
}
[Table(Name = "SearchParams")]
public class SearchParam
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public Int32 SearchParamID { get; set; }
[Column]
public String ParamValue { get; set; }
// Each search param is associated with one search
[Column]
public Int32 SearchID { get; set; }
private EntityRef<Search> search = new EntityRef<Search>();
[Association(Storage = "search", ThisKey = "SearchID", OtherKey = "SearchID", IsForeignKey = true)]
public Search Search
{
get
{
return search.Entity;
}
set
{
search.Entity = value;
}
}
}
So with the above code, if I were to do something like the following, .NET gives me a NullReferenceException
on SubmitChanges
:
using (SampleDataContext context = new SampleDataContext())
{
Search search = new Search();
search.SearchParams.Add(new SearchParam() { ParamValue = "...paramvalue..." });
context.Searches.InsertOnSubmit(search);
context.SubmitChanges();
}