473,569 Members | 2,692 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Send Strongly-typed Dataset with Multiple Tables to SQL Server

New to DOTNET so please be gentle:

I have an in-memory dataset that I want move to a SQL Server database.
The XML schema with which the dataset was built matches exactly the
table schema in SQL Server (same fields, same relations, etc.).

The dataset has eight tables all of which are linked to each other by
an identity field.

From what I understand, I should be able to "flush" the data from the
dataset in memory to the tables in SQL Server with just a few lines of
code.

I've been googling all afternoon but have had no success to point me
in the right direction.

Am I on the right track? Is there a way to move the data to SQL
Server at once?
Nov 21 '05 #1
8 6874
(If you are using a sqldataadapter)
Call the update method of the dataadapter passing the dataset as as argument.
"Dot Net Newbie" <si******@dodge it.com> wrote in message
news:a4******** *************** ***@posting.goo gle.com...
New to DOTNET so please be gentle:

I have an in-memory dataset that I want move to a SQL Server database.
The XML schema with which the dataset was built matches exactly the
table schema in SQL Server (same fields, same relations, etc.).

The dataset has eight tables all of which are linked to each other by
an identity field.

From what I understand, I should be able to "flush" the data from the
dataset in memory to the tables in SQL Server with just a few lines of
code.

I've been googling all afternoon but have had no success to point me
in the right direction.

Am I on the right track? Is there a way to move the data to SQL
Server at once?

Nov 21 '05 #2

"Dot Net Newbie" <si******@dodge it.com> wrote in message
news:a4******** *************** ***@posting.goo gle.com...
New to DOTNET so please be gentle:

I have an in-memory dataset that I want move to a SQL Server database.
The XML schema with which the dataset was built matches exactly the
table schema in SQL Server (same fields, same relations, etc.).

The dataset has eight tables all of which are linked to each other by
an identity field.

From what I understand, I should be able to "flush" the data from the
dataset in memory to the tables in SQL Server with just a few lines of
code.

I've been googling all afternoon but have had no success to point me
in the right direction.

Am I on the right track? Is there a way to move the data to SQL
Server at once?


Minimally,

Dim ds As DataSet
Dim con As SqlConnection
For Each dt As DataTable In ds.Tables
Dim cmd As New SqlCommand("sel ect * from " & dt.TableName, con)
Dim da As New SqlDataAdapter( cmd)
Dim cb As New SqlCommandBuild er(da)
da.Update(dt)
Next
Now usually you need a bit more, since you won't be able to flush the tables
in just any order. Foreign key relationships will dictate the order. So
actually this is more realistic

Dim ds As DataSet = . . .
'make a copy of the changes for the transaction
Dim changes As DataSet = ds.GetChanges()
Dim con As SqlConnection = ...
Dim tran As SqlTransaction = con.BeginTransa ction()
Try
For Each tn As String In New String() {"Table1", "Table2",
"Table3"}
Dim dt As DataTable = changes.Tables( tn)
Dim cmd As New SqlCommand("sel ect * from " & dt.TableName,
con)
Dim da As New SqlDataAdapter( cmd)
Dim cb As New SqlCommandBuild er(da)
da.InsertComman d = cb.GetInsertCom mand
da.UpdateComman d = cb.GetUpdateCom mand
da.DeleteComman d = cb.GetUpdateCom mand
da.InsertComman d.Transaction = tran
da.UpdateComman d.Transaction = tran
da.DeleteComman d.Transaction = tran
da.Update(dt)
Next
ds.AcceptChange s()
tran.Commit()
Catch ex As Exception
ds.RejectChange s()
tran.Rollback()
Throw
Finally
con.Close()
End Try

Now going one step further you should ditch the CommandBuilder, or use it
only the first time and save the Insert, Update and Delete commands for each
table since it's expensive to recreate them every time.

David
Nov 21 '05 #3
DotNetNewbie,

In your situation I would do it like this.
(Use in the beginning a global dataset and global dataadapter as I show you
beneath somewhere in top of your program outside a method)

private ds as new dataset
private da as new SQLDataadapter

In the load event of the form

I would do see this sample
http://msdn.microsoft.com/library/de...chematopic.asp

However with a Select string as "Select * from mytable" and than of course
da.fillschema(d s)
Than directly
dim cmb as new commandbuilder( da).

In a let say button event I would than do after reading the dataset with by
instance readXML.
dim ds as dataset = Mystronglytyped Dataset

And than
try
da.update(ds)
catch ex as exception
'errror handling
end try

You do not need to open and close connections for this, that is all done by
the dataadapter.

I hope this helps a little bit?

Cor


"Dot Net Newbie" <si******@dodge it.com>
New to DOTNET so please be gentle:

I have an in-memory dataset that I want move to a SQL Server database.
The XML schema with which the dataset was built matches exactly the
table schema in SQL Server (same fields, same relations, etc.).

The dataset has eight tables all of which are linked to each other by
an identity field.

From what I understand, I should be able to "flush" the data from the
dataset in memory to the tables in SQL Server with just a few lines of
code.

I've been googling all afternoon but have had no success to point me
in the right direction.

Am I on the right track? Is there a way to move the data to SQL
Server at once?

Nov 21 '05 #4
Hi Guys,

Thanks so much for the responses. All of you have definitely helped
me progress further. However, I'm still not getting the desired
results. So far, what Mark and David have suggested works for the
Parent table, but I can't get it to work for children.
=============== ==============
Here are the details for Mark
=============== ==============
I was not using the SQL Adapter so I added two new ones to the form.
I used the "Wizard" on each one to bind a table from the database. As
you probably already know, when you add a SQL adapter, VB also creates
a new sql connection (SqlConnection1 ) on the form as well.

When I added the second adapter, no new SQL Connection was created.
I'm *assuming* it's using the one created by SQLAdapter1; especially
since I was able to select my child table from Query builder.

Ok, so now I have a form with two sql adapters and one sql connection.
I run through my code that builds the dataset and then add the
following lines:
myForm.sqlAdapt er1.Update(myDa taset) 'adapter for Parent Table
myForm.sqlAdapt er2.Update(myDa taset) 'adapter for Child Table

The first line works. My record inserts beautifully. The second one
however, does nothing. No new record, no error message, no nothing.

I can tell *something* has happened. When I check the parameters for
the InsertCommand between the two data adapters, Adapter1 has the
values that were inserted but Adapter2 has no parameter values.

Also, the rowstate of row(0) for the Parent Table has been set to
"unchanged" whereas the rowstate of row(0) for the Child Table is
still set to "Added".

Any ideas why the line of code runs without error for the child table
yet nothing happens in the database?
Nov 21 '05 #5
Hi Guys,

Thanks so much for the responses. All of you have definitely helped
me progress further. However, I'm still not getting the desired
results. So far, what Mark and David have suggested works for the
Parent table, but I can't get it to work for children.

=============== =====
Here are the details
=============== =====
Hey David,

Your sample code really helped me.

There were a couple of changes I had to make in order for it to work
(just in case someone else needs it):
con.Open() 'before dimensioning transaction
cmd.Transaction = tran 'before setting da commands (that's da as in
Data DataAdapter not the slang form of "the" :) )
The problem I had, as with Mark was adding the child records. I DID
get an error message with your code though.
When I execute "da.update(dt)" , I ge this error message:
Run-time exception thrown : System.Data.Sql Client.SqlExcep tion -
INSERT statement conflicted with COLUMN FOREIGN KEY constraint
'Parent_To_Chil d'. The conflict occurred in database 'myDatabase',
table 'Parent', column 'ParentID'.
The statement has been terminated.

Assume in my child table, I have a foreign key called "ParentID" and
that it's an identity field. It's a negative number b/c this record
will be new everytime. I was pretty sure I read somewhere that when
you try to do what I'm doing, you want to use negative numbers for you
IDs so that DOT Not will know to add it as a new reocord and change
child keys appropriately.

But, my keys aren't changing. Any other help?
Nov 21 '05 #6

"Dot Net Newbie" <si******@dodge it.com> wrote in message
news:a4******** *************** ***@posting.goo gle.com...
Hi Guys,

Thanks so much for the responses. All of you have definitely helped
me progress further. However, I'm still not getting the desired
results. So far, what Mark and David have suggested works for the
Parent table, but I can't get it to work for children.

=============== =====
Here are the details
=============== =====
Hey David,

Your sample code really helped me.

There were a couple of changes I had to make in order for it to work
(just in case someone else needs it):
con.Open() 'before dimensioning transaction
cmd.Transaction = tran 'before setting da commands (that's da as in
Data DataAdapter not the slang form of "the" :) )
The problem I had, as with Mark was adding the child records. I DID
get an error message with your code though.
When I execute "da.update(dt)" , I ge this error message:
Run-time exception thrown : System.Data.Sql Client.SqlExcep tion -
INSERT statement conflicted with COLUMN FOREIGN KEY constraint
'Parent_To_Chil d'. The conflict occurred in database 'myDatabase',
table 'Parent', column 'ParentID'.
The statement has been terminated.

Assume in my child table, I have a foreign key called "ParentID" and
that it's an identity field. It's a negative number b/c this record
will be new everytime. I was pretty sure I read somewhere that when
you try to do what I'm doing, you want to use negative numbers for you
IDs so that DOT Not will know to add it as a new reocord and change
child keys appropriately.


http://msdn.microsoft.com/library/de...anidcrisis.asp
http://support.microsoft.com/default...en-us%3B310350
David
Nov 21 '05 #7
I was able make it work with data adapters as follows:
myAdapter1.Inse rtCommand.Updat edRowSource =
UpdateRowSource .FirstReturnedR ecord
myAdapter1.Upda te(myDataset.Ta bles("ParentTab le"))

myAdapter2.Inse rtCommand.Updat edRowSource =
UpdateRowSource .FirstReturnedR ecord
myAdapter2.Upda te(myDataset.Ta bles("ChildTabl e"))

After running the code with the UpdatedRowSourc e property set, I
checked my key values:
myDataset.Table s("ChildTable") .row(0).item("P rimaryKey")
myDataset.Table s("ChildTable") .row(0).item("P arentForeignKey ")

They were both automatically updated with the new values from SQL
server; just as I'd hoped :)


Tinkerbee
Nov 21 '05 #8
That link was EXACTLY what I was looking for! Thanks!

FYI: I still could not get your snippit of code to work.

I think I'm missing something obvious since I was able to acheive my
goal with Adapters located on Windows forms.

I tried something similar (inserted these two lines below "Dim cb As
New SqlCommandBuild er(da)":
da.InsertComman d.UpdatedRowSou rce =
UpdateRowSource .FirstReturnedR ecord
da.InsertComman d.CommandText = sCommandTextStr ing 'where
sCommandTextStr ing is the same InsertCommand.C ommand text from
myAdapter1.Inse rtCommand.Comma ndText

I compared the properties between the two adapters "da" and
"Adapater1" . They were the same.

However, after running the update command, my Primary Key value is
still -1.

It's not that big a deal since I have what I need.

However, if you're still willing to help troubleshoot, I wouldn't mind
seeing the solution :)
Nov 21 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2596
by: MrMagooba | last post by:
Hi, I have a contact page that, when submit is clicked it checks the inputs then outputs to a "read only" version of the input form fromwhich the email can be sent. How would I go about changing the script so when the submit button is clicked, it'll check, and if it passes the requirements, it'll be sent (to the formmail script)? You can...
1
2246
by: Jack Menendez | last post by:
I have a forms based plugin architecture using C# that includes help files using MSHelpServices. However, my strongly named assemblies cannot be created because Interop.MSHelpServices is not strongly named. I get the following message during a build, presumedly from AL.exe: Assembly generation failed -- Referenced assembly...
36
3254
by: dcrespo | last post by:
Hi all, I have a program that serves client programs. The server has a login password, which has to be used by each client for logging in. So, when the client connects, it sends a string with a password, which is then validated on the server side. The problem is obvious: anyone can get the password just sniffing the network. How can I...
4
1665
by: Tamir Khason | last post by:
I have a form. On form there is my control (all of control's assemblies signed by strong key), BUT while running I recieve he located assembly 'MyFooAssembly' is not strongly named. While looking into References node in project the assembly 'MyFooAssembly' is strong key = true. So what cna be a ptoblem??? TNX
1
1388
by: San | last post by:
Hi, Why strongly named assembly can refer other strongly named assembly ? Thanks with Regards, San.
5
1529
by: Oleg Subachev | last post by:
When I try to use strongly named assembly1 that references non-strongly named assembly2 I get the following error: "The located assembly '<assembly2 name>' is not strongly named." How can I force strongly named assembly1 to reference non-strongly named assembly2 ? --
7
1383
by: rom | last post by:
i know it's not exactly the place to post this question but i didn't find a betrer group. when i send a zipped folder with an asp.net application i cant use it on the destination computer. when i open the solution i cant see the vb.net files. they appear with a yellow ! sign on them.
1
1432
by: DotNetJunkies User | last post by:
I have a .NET DLL that uses ADO 2.8 DLL. I am not able to "strongly name" the .NET DLL. Any comments, work arounds ? CHDe --- Posted using Wimdows.net NntpNews Component -
2
2133
by: Charlie Brown | last post by:
I can open an application such as Notepad and use SendKeys to send input to the Notepad. What I would like to do is reference an already running application and then send keyboard input to it. Any thoughts? Can this be done with sendkeys or is there another method.
0
1568
by: Dave Burns | last post by:
Hi, I have a C++ managed assembly (.dll) which links to a bunch of native libraries. Everything works fine if I don't make the managed assembly a strongly named one. Once I make it a strongly named assembly by adding the following attribute: ;
0
7698
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7612
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7970
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6284
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5513
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3640
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.