Home Backend Development C#.Net Tutorial ASP.NET MVC uses stored procedures to add and modify data operations in batches

ASP.NET MVC uses stored procedures to add and modify data operations in batches

Feb 20, 2017 pm 05:11 PM

This article mainly introduces the method of batch adding and modifying data in ASP.NET MVC using stored procedures. It is very good and has reference value. Friends in need can refer to

Using Entity Framework for database interaction. Directly use lambda expressions and linq to operate the database in the code, which saves programmers the coding time for database access. Programmers can directly focus on writing the business logic layer. However, it is more laborious to query or modify more complex table relationships. The usual method that can be adopted is to use EF to execute SQL statements or "stored procedures", especially to execute complex batch tasks. Of course, you can also use ADO.NET at the bottom of MVC, which I won't go into here. How to make batches? Here we talk about using stored procedures to add and modify data in batches under EF.

The requirements are as follows: the amount of delivery tasks for product categories needs to be added and modified in batches. It is updated once a month and resets to 0 at the beginning of the month. After being added, it will be displayed in the form, that is, the addition and modification are all on one page.

ASP.NET MVC用存储过程批量添加修改数据操作

Idea: The front-end first uses a form to dynamically read the category, and uses viewbag to dynamically load it into the page. If there is already After adding the number of tasks for the current month, it will be read and displayed on the form, which can be modified. Otherwise, the number of tasks for the current month will be newly added. When submitting the form, a problem arose. How to post the category number to the backend? I thought of a way, that is, add a hidden field with the value "Type|Category Number". The backend gets the data to determine whether it contains Type. is the category number, then use split('|')[1] to read it in a loop.

How to pass it to the database? I save the data into the datatable, then use EF to execute the stored procedure, and pass the datatable to the database as parameters for processing.

How does the database handle this datatable? Processing

Code steps with custom data types:

Code aspects

Controller display Dynamic form

public ActionResult MarketTaskAdd()
  {
   var markeType = new MarketDataProvider().GetBTIDData().Where(a=>a.ID!="0");//读取类别
   var rel = new MarketTaskProgressProvider().GetMarketMonthTask();
   if (rel.Count() > 0)
   {
    ViewBag.datas = rel.Join(markeType, a => a.MKBTID, b => int.Parse(b.ID), (a, b) => new { a.MKBTID, b.ID,b.Text,a.TaskNum }).Select(s=>new ViewsModel { ID= s.MKBTID.ToString() ,Text=s.Text,TaskNum=s.TaskNum.ToString()}); }//如果有数据关联数据
   else
   {
    var rel2 = markeType.Select(s => new ViewsModel{ ID = s.ID, Text = s.Text, TaskNum="" }).ToList();//直接返回表单
    ViewBag.datas = rel2;
   }
   return View();
  }
Copy after login

At first I wanted to return object directly, but the foreground traversal was not supported, so I created a new entity class ViewsModel.

View page

@foreach (var modelMarkets in ViewBag.datas)
       {
        <p class="row" style="margin-top:10px">
         <p class="col-md-4 text-right"><span class="red">*</span> @modelMarkets.Text </p>
         <p class="col-md-8 text-left">
          <input name="text|@modelMarkets.ID" class="form-control" style="width:50%" value="@modelMarkets.TaskNum" type="text" />
          <input type="hidden" name="type|@modelMarkets.ID" value="type|@modelMarkets.ID" /><!--隐藏表单-->
         </p>
        </p>
       }
Copy after login

Controller post submission form

[HttpPost]
  public ActionResult MarketTaskAdd(string type)
  {
   var strform = Request.Form;
   int userId = adminUser!=null?adminUser.UserID:0;//创建人或者修改人ID
   DataTable dt = new DataTable();
   dt.Columns.Add("MKBTID",Type.GetType("System.Int32"));
   dt.Columns.Add("TaskNum", Type.GetType("System.Int32"));
   List<string> temp1 = new List<string>();
   List<string> temp2 = new List<string>();
   for (int i = 0; i < strform.Count; i++)
   {
    if (strform[i].Contains("type"))
    { temp1.Add(strform[i].Split(&#39;|&#39;)[1]); }
    else
    { temp2.Add(strform[i]); }//循环分解表单
   }
   for (int i = 0; i < temp1.Count; i++)
   {
    DataRow dr = dt.NewRow();
    dr[0] = temp1[i];
    dr[1] = temp2[i];
    dt.Rows.Add(dr);//批量添加到datatable
   }
   var rel = new MarketTaskProgressProvider().MarketTaskAddOrEdit(userId,dt);//调用方法
   if(rel)
     ViewBag.js = "<script>alert(&#39;操作成功!&#39;);window.location.href=&#39;/MarketTaskProgress/MarketTaskAdd&#39;;</script>";
   else
    ViewBag.js = "<script>alert(&#39;操作失败!&#39;);window.location.href=&#39;/MarketTaskProgress/MarketTaskAdd&#39;;</script>";
   List<ViewsModel> listTemp = new List<ViewsModel>();
   listTemp.Add(new ViewsModel
   {
    ID = "",
    Text = "",
    TaskNum = ""
   });
   ViewBag.datas = listTemp;
   return View();
  }
 }
Copy after login

Submit to database method:

public bool MarketTaskAddOrEdit(int userId,DataTable dt)
  {
   using (DssEntity entity = new DssEntity())//不推荐用using
   {
    SqlParameter p = new SqlParameter("@CreatedUser",DbType.Int32);
    p.Value = userId;
    SqlParameter p1 = new SqlParameter("@tableMarketTask",DbType.Object);
    p1.Value = dt;
    p1.TypeName = "tableMarketTask";//参数处理,貌似自定义函数必须加这个函数名称
    var rel = entity.Database.ExecuteSqlCommand("EXEC[dbo].[PR_MarketTaskAddorEdit] @CreatedUser,@tableMarketTask", p,p1);//ef执行存储过程
    return rel > 0;
   }
  }
Copy after login

##Database aspect

First create a custom type according to the situation, as follows

-- Create the data type
CREATE TYPE [dbo].[tableMarketTask] AS TABLE(
 [MKBTID] [varchar](50) NOT NULL,--投放类别
 [TaskNum] [varchar](50) NOT NULL--投放任务数量
)
Copy after login

 You can also use the sql server tool to manually create a new one

The second is to build a stored procedure

CREATE PROCEDURE PR_MarketTaskAddorEdit
 @CreatedUser INT,
 @tableMarketTask tableMarketTask readonly --自定义类型的参数,必须加readonly。
AS
 DECLARE @TempCreatedUser INT
 IF EXISTS(SELECT TOP 1 * FROM MarketMonthTask T WHERE Months=MONTH(GETDATE()))--当月存在的话就修改
 BEGIN
  SELECT TOP 1 @TempCreatedUser=CreatedUser FROM MarketMonthTask T WHERE Months=MONTH(GETDATE())
  DELETE FROM MarketMonthTask WHERE Months=MONTH(GETDATE())
  INSERT INTO MarketMonthTask(MKBTID,TaskNum,Months,UpdateUser,CreatedUser) SELECT MKBTID,TaskNum,MONTH(GETDATE()),@CreatedUser,@TempCreatedUser FROM @tableMarketTask
 END
 ELSE--或者直接插入
 BEGIN
  INSERT INTO MarketMonthTask(MKBTID,TaskNum,Months,CreatedUser) SELECT MKBTID,TaskNum,MONTH(GETDATE()),@CreatedUser FROM @tableMarketTask
 END
Copy after login

Custom types can be queried by themselves like tables, which is very convenient. Custom functions are not easy to debug. EF does not support custom functions when calling stored procedures directly.

The above is the ASP.NET MVC batch adding and modifying data operation using stored procedures introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will promptly Reply to everyone. I would also like to thank you all for your support of the PHP Chinese website!

For more articles related to ASP.NET MVC using stored procedures to add and modify data in batches, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the alternatives to NULL in C language What are the alternatives to NULL in C language Mar 03, 2025 pm 05:37 PM

This article explores the challenges of NULL pointer dereferences in C. It argues that the problem isn't NULL itself, but its misuse. The article details best practices for preventing dereferences, including pre-dereference checks, pointer initiali

How to add next-level C compiler How to add next-level C compiler Mar 03, 2025 pm 05:44 PM

This article explains how to create newline characters in C using the \n escape sequence within printf and puts functions. It details the functionality and provides code examples demonstrating its use for line breaks in output.

Which C language compiler is better? Which C language compiler is better? Mar 03, 2025 pm 05:39 PM

This article guides beginners on choosing a C compiler. It argues that GCC, due to its ease of use, wide availability, and extensive resources, is best for beginners. However, it also compares GCC, Clang, MSVC, and TCC, highlighting their differenc

Is NULL still important in modern programming in C language? Is NULL still important in modern programming in C language? Mar 03, 2025 pm 05:35 PM

This article emphasizes the continued importance of NULL in modern C programming. Despite advancements, NULL remains crucial for explicit pointer management, preventing segmentation faults by marking the absence of a valid memory address. Best prac

What are the web versions of C language compilers? What are the web versions of C language compilers? Mar 03, 2025 pm 05:42 PM

This article reviews online C compilers for beginners, focusing on ease of use and debugging capabilities. OnlineGDB and Repl.it are highlighted for their user-friendly interfaces and helpful debugging tools. Other options like Programiz and Compil

C language online programming website C language compiler official website summary C language online programming website C language compiler official website summary Mar 03, 2025 pm 05:41 PM

This article compares online C programming platforms, highlighting differences in features like debugging tools, IDE functionality, standard compliance, and memory/execution limits. It argues that the "best" platform depends on user needs,

Method of copying code by C language compiler Method of copying code by C language compiler Mar 03, 2025 pm 05:43 PM

This article discusses efficient code copying in C IDEs. It emphasizes that copying is an IDE function, not a compiler feature, and details strategies for improved efficiency, including using IDE selection tools, code folding, search/replace, templa

How to solve the problem of not popping up the output window by the C language compiler How to solve the problem of not popping up the output window by the C language compiler Mar 03, 2025 pm 05:40 PM

This article troubleshoots missing output windows in C program compilation. It examines causes like failing to run the executable, program errors, incorrect compiler settings, background processes, and rapid program termination. Solutions involve ch

See all articles