【问题标题】:Assigning entity id from code, not by database, two request at the same time从代码中分配实体ID,而不是通过数据库,同时两个请求
【发布时间】:2018-02-14 23:24:47
【问题描述】:

嘿,我想将一些代表树结构类型的对象放入数据库:

每个 TreeNode 元素,必须有唯一的 id。

我的树节点

public class TreeNode
{
    public int Id { get; set; }
    public int ParentId { get; set; }
}

我从应用程序前端收到的数据

  {
    "name": "Tree Node 1",
    "children": 
    [{
        "name": "Tree Node 2",
        "children": 
        [{
            "name": "Tree Node 3",
            "children": 
            [{
                "name": "Tree Node 4",
                "children": 
                [{
                    "name": "Tree Node 5",
                    "children": 
                    [{
                        "name": "Tree Node 6",
                        "children": [],
                        "data": 
                        {
                        }
                    }]
                }, 
                {
                    "name" : "Tree Node embeded parent 4",
                    "children": [],
                    "data": 
                    {

                    }
                }]
            }]
        }]
    }]
} 

我的问题是 - 如何为每个节点分配正确的 Id?

我当前的解决方案是,我从数据库中获取最后插入的 Id,并使用它来分配给 concreate TreeObject。它有效,但我觉得它不够好。

这种解决方案至少有一个很大的缺点——如果两个用户同时尝试将数据推送到数据库中会怎样?

假设用户 A,点击了“保存”按钮。 TreeProcessor 从数据库中接收到 100 是最后插入的 Id 的信息。 在 TreeProcessor 以处理数据结束(例如分配 ids)后, 数据已准备好发送到数据库,但突然网络连接变慢...

同时,用户 B 也单击了“保存”,但使用了另一个数据。 由于来自用户 A 的数据,尚未到达数据库,数据库发送 100 作为最后插入的 id .....

【问题讨论】:

  • 使用 Guid 作为密钥,public Guid Id { get; set; }。

标签: c# asp.net .net sql-server asp.net-core


【解决方案1】:

你能在你的数据库表中使用一个标识列,并让数据库处理分配 ID 吗?创建一个插入并返回使用的标识的过程,沿着树向下工作。

或者将操作封装在一个事务中,这样用户 B 在用户 A 写入他的数据之前无法获得 id。 Google TransactionScope 了解如何在 C# 中执行此操作,或者如果可能的话在数据库中执行此操作(无法从问题中完全辨别您的整体架构)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-28
    • 2012-11-20
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多