0

我想通过使用 BLToolkit 在父/子关系中的一组表中添加一些新记录。不幸的是,我无法弄清楚我错过了什么,因为在提交之后,我的数据库中只有父行。

当我在将父对象添加到父对象列表之前检查父对象时,它包含预期的子对象。我很确定我在 SQLQuery-Bit 中遗漏了一些东西,但我不知道是什么。

这是我设置的东西。

  • 创建表的sql代码
    CREATE TABLE [dbo].[PARENTS](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [SOME_VALUE] [int] NOT NULL,
        CONSTRAINT [PK_PARENT] PRIMARY KEY CLUSTERED 
        (
            [ID] ASC
        )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    CREATE TABLE [dbo].[CHILDS](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [PARENT_ID] [int] NOT NULL,
        [SOME_TEXT] [nvarchar](50) NOT NULL,
        CONSTRAINT [PK_CHILD] PRIMARY KEY CLUSTERED 
        (
            [ID] ASC
        )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO

    ALTER TABLE [dbo].[CHILDS]  WITH CHECK ADD  CONSTRAINT [FK_CHILD_PARENT] FOREIGN KEY([PARENT_ID])
    REFERENCES [dbo].[PARENTS] ([ID])
    GO

    ALTER TABLE [dbo].[CHILDS] CHECK CONSTRAINT [FK_CHILD_PARENT]
  • 班级
[TableName("PARENTS")]
public class Parent
{
    public Parent()
    {
        Children = new List<Child>();
    }

    [MapField("ID"), PrimaryKey, NonUpdatable]
    public int Id;

    [MapField("SOME_VALUE")]
    public int SomeValue;

    [Association(ThisKey = "ID", OtherKey = "PARENT_ID", CanBeNull = false)]
    public List<Child> Children;
}

[TableName("CHILDS")]
public class Child
{
    [MapField("ID"), PrimaryKey, NonUpdatable]
    public int Id;

    [MapField("SOME_TEXT")]
    public string SomeText;

    [Association(ThisKey = "PARENT_ID", OtherKey = "ID", CanBeNull = false)]
    public Parent Parent;
}
  • 插入行的代码
using (DbManager db = new DbManager())
{
    db.BeginTransaction();
    SqlQuery<Parent> query = new SqlQuery<Parent>();

    IList<Parent> parents = new List<Parent>();
    for (int i = 0; i < 10; i++)
    {
        Parent parent = new Parent();
        parent.SomeValue = i;

        Child child = new Child();
        child.SomeText = i.ToString();

        parent.Children.Add(child);
        parents.Add(parent);
    }
    query.Insert(db, 10, parents);
    db.CommitTransaction();
}
4

1 回答 1

2

您的代码没有任何问题。BLToolkit 是一个轻量级的 ORM,这意味着它不会跟踪对象的状态。这与 EF、L2SQL、NHibernate 等其他 ORM 不同。在 BLToolkit 中,您直接使用数据库。你应该做的是:

  1. 插入 Parent 并获取它的身份。
  2. 然后插入孩子并将其设置为父ID。

此外,当您插入/更新或删除时,请在 try/catch 中执行此操作,如下所示

using (DbManager db = new DbManager())
{
    try
    {
        db.BeginTransaction();

        // do something here...

        db.CommitTransaction();
    }
    catch
    {
        db.RollbackTransaction();
    }
}
于 2012-08-07T20:01:47.667 回答