我在这里束手无策。问题是我试图在数据库中创建一个新实体,使用 db 生成的标识属性,在 LINQ to SQL 中,然后创建另一个与第一个实体相关联的实体。我猜问题是 LINQ to SQL 无法插入第二个实体,而没有来自第一个实体的 id,直到数据库生成它才会知道。
有没有其他人遇到过这个问题...如果是这样,您是如何解决的?我知道我可以SubmitChanges
在创建第一个和第二个实体之间调用,但这会破坏程序的事务完整性。
这是一个具体的例子:
[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;
}
}
}
因此,使用上面的代码,如果我要执行以下操作,.NET 会给我一个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();
}