使用LINQ2SQL插入新的子级+父级 [英] Insert new child+parent with LINQ2SQL

查看:80
本文介绍了使用LINQ2SQL插入新的子级+父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在LINQ2SQL上苦苦挣扎,这是我的新手,到目前为止还可以,但是这个问题确实让我感到悲伤.

struggling with LINQ2SQL, I'm new to it, and so far it's been ok, but this problem is really causing me grief.

我有两个对象,父对象和子对象,

I've got two objects, Parent and Child, defined as such

[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.

If I remove the relationship between the two tables in the DB and save, they save ok. Except that the ParentID in the Child record always stays as 0.

如果我在数据库中创建该关系并尝试保存该关系,它将失败,这显然是因为Child的ParentID为0会破坏参照完整性.

If I create the relationship in the DB and try to save, it fails, obviously because the Child have a ParentID of 0 would break referential integrity.

即使我将以上内容修改为

Even if I modify the above to be;

Parent newParent = new Parent();
Child newChild = new Child();
newChild.ParentID = newParent.ParentID;
newParent.Children.Add(newChild);
parentTable.InsertOnSubmit(newParent);
parentTable.Context.SubmitChanges();

为什么这不起作用?我在Linq2SQL中缺少什么?

Why is this not working? What am I missing in Linq2SQL?

任何帮助,不胜感激!

推荐答案

请在您的项目中添加一个新项目:前缀为'.dbml'LINQ to SQL classes mapped to relational objects.,然后将表添加到设计器界面中,因此VS将自动为您创建实体映射和相关关系,
P.S.:别忘了为每个表设置一个primary key,否则没有一个可以完美地工作

Please add a new item: LINQ to SQL classes mapped to relational objects. with prefix '.dbml' to your project and then add tables to the designer interface, thus the VS will automatically create the entities mapping and related relations for you,
P.S.: Don't forget to set a primary key to each table otherwise none will work perfectly

这篇关于使用LINQ2SQL插入新的子级+父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆