与 LINQ2SQL 作斗争,我是新手,到目前为止一切都还好,但这个问题确实让我悲伤。
我有两个对象,父对象和子对象,定义如下
[Table(Name="Parent")]
public class Parent
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public int ParentID { get; set; }
[Association(OtherKey = "ParentID")]
protected EntitySet<Child> _children = new EntitySet<Child>();
public IList<Child> Children
{
get { return _children.ToList(); }
set { _children (value); }
}
}
[Table(Name="Child")]
public class Child
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public int ChildID { get; set; }
[Association(OtherKey = "ParentID", IsForeignKey=true)]
[Column] public int ParentID { get; set; }
}
我接下来要做的基础是
Parent newParent = new Parent();
Child newChild = new Child();
newParent.Children.Add(newChild);
parentTable.InsertOnSubmit(newParent);
parentTable.Context.SubmitChanges();
如果我删除数据库中两个表之间的关系并保存,它们就可以保存。只是子记录中的 ParentID 始终保持为 0。
如果我在数据库中创建关系并尝试保存,它会失败,显然是因为 Child 的 ParentID 为 0 会破坏引用完整性。
即使我将上面修改为;
Parent newParent = new Parent();
Child newChild = new Child();
newChild.ParentID = newParent.ParentID;
newParent.Children.Add(newChild);
parentTable.InsertOnSubmit(newParent);
parentTable.Context.SubmitChanges();
为什么这不起作用?我在 Linq2SQL 中缺少什么?
非常感谢任何帮助!