设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 1307|回复: 2

Bulk INSERT / UPDATE / DELETE in LINQ to SQL

[复制链接]
发表于 2011-5-24 14:06:07 | 显示全部楼层 |阅读模式
IntroductionLINQ to SQL is great as an ORM tool. It provides ease of access to data in our data oriented applications. It is also very easy to learn. In this article, we will be discussing about SET based operations for database operations using LINQ to SQL.
BackgroundLike many other ORMs, it is not very good with data insertion, manipulation, and deletion. Though it does allow all of these operations, all of these operations are not efficient in terms of the performance standpoint of applications involving large data manipulations. These operations are submitted to the database as soon as we call the submitChanges() method of our DataContext object. These are submitted as individual INSERT, UPDATE, or DELETE statements for each record involved. You might notice these statements using SQL Profiler when the submitChanges() method is called.
Since the system does not support bulk insertion, manipulation, or deletion out of the box, we need to provide this functionality ourselves.
DiscussionWe know that LINQ to SQL supports Stored Procedures as a first class citizen through DataContext. Like entities, we need to add the definition of the Stored Procedures to our DBMLs. The solution proposed here would use a Stored Procedure. This is not a generic solution, but would help in doing bulk operations with your database entities. Those who have been doing bulk database operations in .NET might have used similar solutions using datasets. This involves sending XML to the Stored Procedures and using OpenXML for applying SET based operations to our data.
To present the solution, let us create a table in the database. I am using SQL Server 2005. We are creating a table named TBL_TEST_TEST with two columns (ID and Name). Here, ID is an identity column which is the primary key of the table.
Collapse
CREATE TABLE [dbo].[TBL_TEST_TEST](    ID INT IDENTITY(1,1) PRIMARY KEY,    [NAME] [varchar](50) )We create a C# console project named TestIQueryable.csproj.

Now, we add a LINQ to SQL class item to our project, named Test.dbml.

Add a connection to your database in Server Explorer, and drop TBL_TEST_TEST to the LINQ to SQL designer for Test.dbml.

Now let us discuss about each operation separately.
Bulk InsertLet us start with the insertion of bulk data in our database. We create a Stored Procedure in the database as follows:
Collapse
CREATE PROCEDURE [dbo].[spTEST_InsertXMLTEST_TEST](@UpdatedProdData nText)AS  DECLARE @hDoc int     exec sp_xml_preparedocument @hDoc OUTPUT,@UpdatedProdData  INSERT INTO TBL_TEST_TEST(NAME) SELECT XMLProdTable.NAME    FROM OPENXML(@hDoc, 'ArrayOfTBL_TEST_TEST/TBL_TEST_TEST', 2)          WITH (                ID Int,                                 NAME varchar(100)            ) XMLProdTableEXEC sp_xml_removedocument @hDocAs discussed earlier, we are passing XML data to this Stored Procedure in the nText argument. We are using OpenXML to get data and insert into our table.
Now, we open the LINQ to SQL designer for adding this Stored Procedure to Test.dbml. Drag the Stored Procedure from Server Explorer to the tab of the designer set aside for Stored Procedures. Update the name of the Stored Procedure to some thing meaningful. We update the name to insertTestData.

We open Program.cs and write some code to generate data. Add the following code to the Main method of the Program class:
Collapse
using (TestDataContext db = new TestDataContext()){    TBL_TEST_TEST[] testRecords = new TBL_TEST_TEST[50];    for (int count = 0; count < 50; count++)    {        TBL_TEST_TEST testRecord = new TBL_TEST_TEST();        testRecord.NAME = "Name : " + count;        testRecords[count] = testRecord;    }    StringBuilder sBuilder = new StringBuilder();    System.IO.StringWriter sWriter = new System.IO.StringWriter(sBuilder);    XmlSerializer serializer = new XmlSerializer(typeof(TBL_TEST_TEST[]));        serializer.Serialize(sWriter, testRecords);    db.insertTestData(sBuilder.ToString());}You can see that we have neither used db.insertOnSubmit() nor submitChanges(). But we have generated data in an array of TBL_TEST_TEST type objects provided by LINQ to SQL. After generating data in the array, we convert it to XML using XMLSerializer. We pass this XML directly to the Stored Procedure using the DataContext object.
Now finally, we are successful in inserting 50 rows of data in one shot to the database.
Bulk UpdatesYou might be more interested to learn about operations involving IQueryable types. Let us create this Stored Procedure in the database:
Collapse
CREATE PROCEDURE [dbo].[spTEST_UpdateXMLTEST_TEST](@UpdatedProdData nText)AS  DECLARE @hDoc int     exec sp_xml_preparedocument @hDoc OUTPUT,@UpdatedProdData  UPDATE TBL_TEST_TEST SET    TBL_TEST_TEST.NAME = XMLProdTable.NAME FROM OPENXML(@hDoc, 'ArrayOfTBL_TEST_TEST/TBL_TEST_TEST', 2)          WITH (                ID Int,                                 NAME varchar(100)            ) XMLProdTableWHERE    TBL_TEST_TEST.ID = XMLProdTable.ID        EXEC sp_xml_removedocument @hDocWe add the definition of this Stored Procedure to Test.dbml:

You can remove the code written in Program.cs (Main method). Add the following code:
Collapse
using (TestDataContext db = new TestDataContext()){    var myPackages = from tbl in db.TBL_TEST_TESTs select tbl;    foreach (TBL_TEST_TEST t in myPackages)    {        t.NAME = t.NAME + " _Updated";    }    XmlSerializer serializer = new XmlSerializer(typeof(TBL_TEST_TEST[]));    StringBuilder sBuilder = new StringBuilder();    System.IO.StringWriter sWriter = new System.IO.StringWriter(sBuilder);    serializer.Serialize(sWriter, myPackages.ToArray<tbl_test_test>());    db.updateTestData(sBuilder.ToString());}In the above code, we have queried the database using the IQueryable interface. After fetching data, we have updated it using a foreach loop. We have serialized it to XML data, and have written it to StringBuilderObject sBuilder. We have passed this data to the database using the Stored Procedure already added. This way, we achieve sending bulk data to our database for update.
Bulk DeletionNow finally, we discuss about bulk deletion. This would be nearly the same solution. The difference is just that instead of updating, we will be deleting data. Let's attempt to delete all records from the database with the values of ID greater than 25.
Collapse
CREATE PROCEDURE [dbo].[spTEST_deleteTEST_TEST](@UpdatedProdData nText)AS  DECLARE @hDoc int     exec sp_xml_preparedocument @hDoc OUTPUT, @UpdatedProdData  DELETE FROM TBL_TEST_TEST WHERE ID IN (     SELECT XMLProdTable.ID        FROM OPENXML(@hDoc, 'ArrayOfTBL_TEST_TEST/TBL_TEST_TEST', 2)              WITH (                    ID Int,                                     NAME varchar(100)                ) XMLProdTable )EXEC sp_xml_removedocument @hDocAdd the definition of this Stored Procedure to Test.dbml and rename it to deleteTestData.

Like in the Update operation, update the code of the Main method of Program.cs as follows:
Collapse
using (TestDataContext db = new TestDataContext()){    var myPackages = from tbl in db.TBL_TEST_TESTs                         where tbl.ID > 25                        select tbl;    XmlSerializer serializer = new XmlSerializer(typeof(TBL_TEST_TEST[]));    StringBuilder sBuilder = new StringBuilder();    System.IO.StringWriter sWriter = new System.IO.StringWriter(sBuilder);    serializer.Serialize(sWriter, myPackages.ToArray());    db.deleteTestData(sBuilder.ToString());}History
  • Article posted: 01/20/2010.
                                                                                                                                                                                                                                                License                                                This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Author
Muhammad Shujaat Siddiqi

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

×
发表于 2011-6-1 22:58:21 | 显示全部楼层
楼主好帖,不顶不精彩,希望这种帖子以后多一点哈





三仙矛草三仙矛草三仙矛草三仙矛草
发表于 2011-6-2 08:25:51 | 显示全部楼层
三只乌龟来到一家饭馆,要了三份蛋糕。东西刚端上桌,他们发现都没带钱。

大乌龟说:我最大,当然不用回去取钱。

中乌龟说:派小乌龟去最合适。

小乌龟说:我可以回去取钱,但是我走之后,你们谁也不准动我的蛋糕!大乌龟和中乌龟满口答应,小乌龟走了。

因为腹中空空,大中乌龟很快将自己的那份蛋糕吃完了。可是,小乌龟迟迟不见踪影。第三天,大中龟实在饿极了,不约而同地说:咱们还是把小龟的那份吃了罢。

正当他们要动手吃时,隔壁传来小乌龟的声音:“如果你们敢动我的蛋糕,我就不回去取钱了!”



最有效丰胸  
怎样才能丰胸  
最佳丰胸方法  
丰胸产品有哪些   
丰胸最快的方法  
怎么丰胸最好  

减肥丰胸方法  
快速丰胸产品  
什么丰胸产品有效   
安全的丰胸产品  
丰胸用什么产品好  
丰胸明星   
怀孕期怎么丰胸  
丰胸有效方法  
明星丰胸产品  

明星如何丰胸  
明星丰胸秘籍  
那种丰胸产品最有效   
什么丰胸方法最有效  
产后怎么丰胸  
怎么可以丰胸   
如何能丰胸  
如何快速有效丰胸  
产后怎样丰胸
怎么能丰胸
您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )  

GMT-8, 2025-8-26 09:05 , Processed in 0.016963 second(s), 18 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表