简体   繁体   English

如何将数据插入.NET Core API中的多个相关表中?

[英]How to insert data into multiple related tables in .NET Core API?

I want to insert data into multiple related tables, I searched, but everything I've found is insert data into multiple tables that aren't related.我想将数据插入到多个相关表中,我进行了搜索,但我发现的所有内容都是将数据插入到多个不相关的表中。 I have two tables User and OrchardTable, both are related by the user Id, so the primary key of the User table is the Id, which is generated as an identity on the database, and the foreign key of the table OrchardTable is the User Id.我有两张表User和OrchardTable,都是通过用户Id关联的,所以User表的主键是Id,在数据库上作为身份生成,OrchardTable表的外键是UserId .

This is from my controller这是来自我的 controller

[HttpPost]
public ActionResult post([FromBody] Models.Users u)
{
    using (Models.OrchardAdminContext db = new Models.OrchardAdminContext())
    {
        Models.User oUser = new Models.User();

        Models.OrchardTable userOrchar = new Models.OrchardTable();

        oUser.Name = u.Name;
        oUser.Email = u.Email;
        db.User.Add(oUser);
        db.SaveChanges();
        
        var idUser = db.OrchardTable.Where(x => x.email = oUser.Email).FirstOrDefault();
        userOrchar.IdUser = idUser.Id;
        userOrchar.orchardUbication = u.ubication;
        db.OrchardTable.Add(userOrchard);
        db.SaveChanges();
    }
    return Ok();
}

So, the code above do: first adds an user to the User table, on the SQL Server Management Studio the Id of each user is an identity therefore when the data is saved the Id is generated and through the mail the id of the user is recovered to make the relation between the tables User and OrchardTable by the Id.因此,上面的代码执行以下操作:首先将用户添加到 User 表中,在 SQL Server Management Studio 上,每个用户的 Id 是一个身份,因此在保存数据时会生成 Id 并通过邮件生成用户的 id恢复以通过 Id 建立表 User 和 OrchardTable 之间的关系。

I think this is a way of do it, but not the best.我认为这是一种方法,但不是最好的。 Besides the main question, I want to know if there are a better and correct way to do the insert.除了主要问题,我想知道是否有更好和正确的插入方法。

Any help is appreciated.任何帮助表示赞赏。

UPDATE Stored procedure to insert into the table User and return the Id from the same instert: UPDATE 存储过程插入到表 User 并从同一个 instert 返回 Id:

GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE spUserInsert 
   @name varchar(20),
   @email varchar(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
   insert into user(name, email) values (@name, @email);
   DECLARE @Id INT  
   SET @Id=@@IDENTITY  
   SELECT @Id AS id
END
GO

So if I'm not mistaken, the idea is to create an SP to insert and return the id of that insert, then with the id send it to another SP where it is inserted into OrchardTable.因此,如果我没记错的话,这个想法是创建一个 SP 来插入并返回该插入的 id,然后使用该 id 将其发送到另一个 SP,并将其插入 OrchardTable。 But now when I call it from the controller it doesn't seem to work because no saved record shows up in the database.但是现在当我从 controller 调用它时,它似乎不起作用,因为数据库中没有显示保存的记录。

The controller: controller:

    [HttpPost]
    public ActionResult post([FromBody] Models.Users u)
    {
        using (Models.OrchardAdminContext db = new Models.OrchardAdminContext())
        {
            Models.User oUser = new Models.User();

            Models.OrchardTable userOrchar = new Models.OrchardTable();

            oUsuar.Name = u.Name;
            oUsuar.Email = u.Email;
            
            var idUserReg = db.User.FromSqlRaw("Execute spUserInsert @name, @email", oUsuar.Name, oUsuar.Email);

            db.SaveChanges();

        }
        return Ok();
    }

I tested the stored procedure on Sql Server and works, but on the controller not, and I don't know why on the controller din't work.我在 Sql 服务器上测试了存储过程并且可以工作,但是在 controller 上没有,我不知道为什么在 controller 上没有工作。 Again, any help is appreciated.再次感谢任何帮助。

Try this:尝试这个:

var pName = new SqlParameter("@name", oUsuar.Name);
var pEmail = new SqlParameter("@email", oUsuar.Email);
            
var idUserReg = db.DataBase.ExecuteSqlCommand("Exec spUserInsert @name, @email", 
new[] { pName, pEmail });

With respect to the procedure to encapsulate the insert, this is what I had in mind you could do关于封装插入物的过程,这是我想到的你可以做的

create procedure UserInsert 
@Name varchar(20),
@Email varchar(100)
<@anyOtherParameters>
as
set nocount, xact_abort on

declare @Id int

begin tran
    insert into [user]([name], email)
    values (@Name, @Email);

    set @Id=Scope_Identity();

    insert into OrchardTable (Id, <othercolumns?>)
    values (@Id, @OtherParams?);
commit tran
go

You only need to make one call from code, the procedure will insert the user , get the identity and then insert this Id into the OrchardTable您只需从代码中进行一次调用,该过程将插入user ,获取identity ,然后将此 Id 插入OrchardTable

If you need to include any other data just pass as paramters also and use for the insert - if you only want a row with the corresponding ID then just leave as a single insert for the Id.如果您需要包含任何其他数据,也只需将其作为参数传递并用于插入 - 如果您只想要具有相应 ID 的行,那么只需将其作为 Id 的单个插入即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将数据播种到 .NET Core 中的多个表? - How to seed data to multiple tables in .NET Core? 具有相关数据的ASP NET Core插入模型 - ASP NET Core Insert Model With Related Data .NET Core 2中多个表的IDENTITY_INSERT - IDENTITY_INSERT for multiple tables in .net core 2 如何将数据发布到.net core restApi 中的多个表? - How to post data to multiple tables in .net core restApi? 如何使用 EF 内核在 Asp.net 内核 web API 中保存相关模型中的数据? - How to save Data in Related Models in Asp.net core web API using EF core? EF插入多个相关表 - EF insert multiple related tables 如何将 api 版本相关数据设置为 httpcontext 以在 .net core 中进行单元测试? - How to set api version related data to httpcontext for unit testing in .net core? 从多个数据库表中检索数据到 ASP.NET Core 中的 API - Retrieve data from multiple database tables to API in ASP.NET Core 如何使用 dbcontext 使用实体框架核心插入一条或多条记录(soap ui 通过 api 调用将数据发送到 asp.net 核心) - How to insert a record or multiple records using entity framework core using dbcontext (soap ui sends data to asp.net core via api call) .NET Core 在实体受保护且属性在洋葱架构中为私有集时,如何在多对多的相关表中保存数据? - How to save data in related tables in many-to-many in .NET Core when the entities are protected and properties are private set in onion architecture?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM