How to use Autocreated DataSet - TableAdapterManager - c#

(Sorry for my bad English)
I have imported an access database to a C# winform project (.net 4.0) in visual studio 2013. It automatically creates a .cs file with a DataSet, TableAdapter and a TableAdapterManager.
I import data from the database to the DataSet, without error. I succeed to manipulate data, and save change to the database with TableAdapterManager.UpdateAll().
But now I try to insert new data, with relation between tables.
For example, a database like mine
Parent table :
autonum key
string parentname
Child table
autonum key
string childname
int parentKey
First try :
I create a new record with parentTable.AddparenttableRow(data ...) and get a parentRow.
I create a new record with childTable.AddchildtableRow(parentRow, data ...)
But if I call TableAdpaterManager.UpdateAll(), I get an error "can't add or modify a record because a related record is required in parentTable" (not the real message, it's a translation). I think that AddchildtableRow create the correct relation. And another problem appears : because of the error, the database isn't modified (which is good), but the records I had add, are always in the table of the DataSet.
So I try another method : TableAdpaterManager.tablenameTableAdpater.Insert()
First I insert a parentRow without any problem. But when I want to insert a childRow, the insert function asks for the parent key. But I don't have it (the insert parent call doesn't return the key).
My question is : how can I use the DataSet, TableAdapter and TableAdapterManager to insert records in the DataSet AND in the database, and with a transaction (if there is an error, the data won't be written to the database, and won't be added to the DataSet) ? And actually, how to correctly use these classes ?

Look up the typed dataset code. Switch between the default TableAdapterManager.UpdateOrderOption.InsertUpdateDelete to UpdateInsertDelete (msdn). For hierarchical updates you have to merge new values for your identity columns (msdn). Also see this post. The way ADO.NET deals with preventing collisions with it's disconnected dataset, it assigns negative IDENTITY column values, because it wouldn't know a possible positive number that IS NOT a collision as it's disconnected. Also managing a ##identity crisis with parent-child relations. The typed dataset technology also had issues with circular table references.

Related

How to copy an entire database with Entity Framework?

The purpose of this task is to copy my database that contains the default values for all entities into a new created database. This task will be called when the program creates the database for the first time, so the newly created database would be filled with the values from my default value database.
The problem with just copy and paste database is that my default value database has messy primary keys. The value of each entity's primary key are not in order.
What I want is to create new database for the program, with the values copied from another database but with continuous primary key for each entity (1,2,3,4,5 no jumping).
The requirement is that the structure, references from the default value database has to remain the solid. For example when copied that entity A reset to id=1 from 5, then all the references changed to 1 as well.
How can I achieve this? Is there a fast way to do it instead of manually copying each entities? Because it is quite a large database.
Note: The default database context is identical to the newly created database context.
I my self done such a task few months back.There is no automatic way.You must do it manually.I would like to share the steps where I have used.
Step 1 :
I have created a new db (i.e. Migrated) by initialling (delete data and PK Reseed) the old db.After that I have an exact copy of the old db (i.e. schema only.No data)
Here is the script for one table
Use Migrated;
GO
delete from IpOccupantNotes
GO
--To Reseed the PK
DBCC CHECKIDENT ('[IpOccupantNotes]', RESEED, 0)
GO
Step 2 :
After that I have inserted the relevant data from the old db (Legacy in my case) as shown below.
INSERT INTO [Migrated].[dbo].[IpOccupantNotes] (Name, ZipCode)
select a.Name,a.ZipCode from [Legacy].[dbo].[IpOccupantNotes] as a;
GO
Note : If you have any question,feel free to ask.I'll help to you :)

Cannot insert data using tableadapter.insert method due to an Auto-Increment field

I need your help since I cannot locate an answer anywhere on the web for my problem.
I'm using C# and I have a table called "People" and I want to use an TableAdapter to add/delete to/form that table. I'm using an sdf file as my database as a "Microsoft SQL Server Compact 4.0 (.NET Framework Data Provider for Microsoft SQL Server Compact 4.0)" Data Source.
my code looks like this:
*peopleTableAdapter.Insert(0, byte.Parse(cbAddType.SelectedIndex.ToString()), txtAddName.Text, txtAddCompany.Text, txtAddPhone.Text,
txtAddMobile.Text, txtAddEmail.Text, txtAddAddress.Text, txtAddNotes.Text);
peopleTableAdapter.Update(this.hisabati_DBDataSet.People);*
the table contains a field called "ID" which is an auto-increment field with the following
attributes:
Allow Nulls: No
Unique: Yes
PK: No
the first param in the Insert method is asking for the ID, and if I don't enter a value, I'll get a compile error that a value is needed. If I enter a value (as I'm entering 0 above) I get the following error:
Err Msg: Cannot modify that column
Err HRESULT: -2147467259
I know how to insert using Command.ExecuteNonQuery method, but I'm trying to use the TableAdapters throughout my application as it looks like a more elegant way to write and maintain the codde...Any Advice?
Thanks much
You need to change the InsertCommand and UpdateCommand of the table adapter. Remove the Auto-Increment column name and values from the set part of those commands.
Instead of using that method specifically, create a new row via your People Dataset, then use the TableAdapter to update from that.

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

I make an outer join and executed successfully in the informix database but I get the following exception in my code:
DataTable dt = TeachingLoadDAL.GetCoursesWithEvalState(i, bat);
Failed to enable constraints. One or more rows contain values
violating non-null, unique, or foreign-key constraints.
I know the problem, but I don't know how to fix it.
The second table I make the outer join on contains a composite primary key which are null in the previous outer join query.
EDIT:
SELECT UNIQUE a.crs_e, a.crs_e || '/ ' || a.crst crs_name, b.period,
b.crscls, c.crsday, c.from_lect, c.to_lect,
c.to_lect - c.from_lect + 1 Subtraction, c.lect_kind, e.eval, e.batch_no,
e.crsnum, e.lect_code, e.prof_course
FROM rlm1course a, rfc14crsgrp b, ckj1table c, mnltablelectev d,
OUTER(cc1assiscrseval e)
WHERE a.crsnum = b.crsnum
AND b.crsnum = c.crsnum
AND b.crscls = c.crscls
AND b.batch_no = c.batch_no
AND c.serial_key = d.serial_key
AND c.crsnum = e.crsnum
AND c.batch_no = e.batch_no
AND d.lect_code= e.lect_code
AND d.lect_code = ....
AND b.batch_no = ....
The problem happens with the table cc1assiscrseval. The primary key is (batch_no, crsnum, lect_code).
How to fix this problem?
EDIT:
According to #PaulStock advice:
I do what he said, and i get:
? dt.GetErrors()[0] {System.Data.DataRow} HasErrors: true ItemArray:
{object[10]} RowError: "Column 'eval' does not allow DBNull.Value."
So I solve my problem by replacing e.eval to ,NVL (e.eval,'') eval.and this solves my problem.
Thanks a lot.
This problem is usually caused by one of the following
null values being returned for columns not set to AllowDBNull
duplicate rows being returned with the same primary key.
a mismatch in column definition (e.g. size of char fields) between the database and the dataset
Try running your query natively and look at the results, if the resultset is not too large. If you've eliminated null values, then my guess is that the primary key columns is being duplicated.
Or, to see the exact error, you can manually add a Try/Catch block to the generated code like so and then breaking when the exception is raised:
Then within the command window, call GetErrors method on the table getting the error.
For C#, the command would be ? dataTable.GetErrors()
For VB, the command is ? dataTable.GetErrors
This will show you all datarows which have an error. You can get then look at the RowError for each of these, which should tell you the column that's invalid along with the problem. So, to see the error of the first datarow in error the command is:
? dataTable.GetErrors(0).RowError
or in C# it would be ? dataTable.GetErrors()[0].RowError
You can disable the constraints on the dataset. It will allow you to identify bad data and help resolve the issue.
e.g.
dataset.TableA.Clear();
dataset.EnforceConstraints = false;
dataAdapter1.daTableA.Fill(dataset, TableA");
The fill method might be slightly different for you.
This will find all rows in the table that have errors, print out the row's primary key and the error that occurred on that row...
This is in C#, but converting it to VB should not be hard.
foreach (DataRow dr in dataTable)
{
if (dr.HasErrors)
{
Debug.Write("Row ");
foreach (DataColumn dc in dataTable.PKColumns)
Debug.Write(dc.ColumnName + ": '" + dr.ItemArray[dc.Ordinal] + "', ");
Debug.WriteLine(" has error: " + dr.RowError);
}
}
Oops - sorry PKColumns is something I added when I extended DataTable that tells me all the columns that make up the primary key of the DataTable. If you know the Primary Key columns in your datatable you can loop through them here. In my case, since all my datatables know their PK cols I can write debug for these errors automatically for all tables.
The output looks like this:
Row FIRST_NAME: 'HOMER', LAST_NAME: 'SIMPSON', MIDDLE_NAME: 'J', has error: Column 'HAIR_COLOR' does not allow DBNull.Value.
If you're confused about the PKColumns section above - this prints out column names and values, and is not necessary, but adds helpful troubleshooting info for identifying which column values may be causing the issue. Removing this section and keeping the rest will still print the SQLite error being generated, which will note the column that has the problem.
Ensure the fields named in the table adapter query match those in the query you have defined. The DAL does not seem to like mismatches. This will typically happen to your sprocs and queries after you add a new field to a table.
If you have changed the length of a varchar field in the database and the XML contained in the XSS file has not picked it up, find the field name and attribute definition in the XML and change it manually.
Remove primary keys from select lists in table adapters if they are not related to the data being returned.
Run your query in SQL Management Studio and ensure there are not duplicate records being returned. Duplicate records can generate duplicate primary keys which will cause this error.
SQL unions can spell trouble. I modified one table adapter by adding a ‘please select an employee’ record preceding the others. For the other fields I provided dummy data including, for example, strings of length one. The DAL inferred the schema from that initial record. Records following with strings of length 12 failed.
This worked for me, source: here
I had this error and it wasn't related with the DB constrains (at least in my case). I have an .xsd file with a GetRecord query that returns a group of records. One of the columns of that table was "nvarchar(512)" and in the middle of the project I needed to changed it to "nvarchar(MAX)".
Everything worked fine until the user entered more than 512 on that field and we begin to get the famous error message "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints."
Solution: Check all the MaxLength property of the columns in your DataTable.
The column that I changed from "nvarchar(512)" to "nvarchar(MAX)" still had the 512 value on the MaxLength property so I changed to "-1" and it works!!.
The problem is with the Data Access designer. In Visual Studio, When we pull a View from "Server Explorer" to the Designer window, it is adding either a Primary key on a column randomly or marking something to a NOT NULL though it is actually set to null. Though the actual View creation in the SQL db server, doesn't have any primary key defined or the NOT NULL defined, the VS designer is adding this Key/constraint.
You can see this in the designer - it is shown with a key icon on left of the column name.
Solution: Right click on the key icon and select 'Delete Key'. This should solve the problem. You can also right click on a column and select "Properties" to see the list of properties of a column in the VS Data access designer and change the values appropriately.
This error was also showing in my project. I tried all the proposed solutions posted here, but no luck at all because the problem had nothing to do with fields size, table key fields definition, constraints or the EnforceConstraints dataset variable.
In my case I also have a .xsd object which I put there during the project design time (the Data Access Layer). As you drag your database table objects into the Dataset visual item, it reads each table definition from the underlying database and copies the constraints into the Dataset object exactly as you defined them when you created the tables in your database (SQL Server 2008 R2 in my case). This means that every table column created with the constraint of "not null" or "foreign key" must also be present in the result of your SQL statement or stored procedure.
After I included all the key columns and the columns defined as "not null" into my queries the problem disappeared completely.
Mine started working when I set AllowDBNull to True on a date field on a data table in the xsd file.
It sounds like possibly one or more of the columns being selected with:
e.eval, e.batch_no, e.crsnum, e.lect_code, e.prof_course
has AllowDBNull set to False in your Dataset defintion.
It is not clear why running a SELECT statement should involve enabling constraints. I don't know C# or related technologies, but I do know Informix database. There is something odd going on with the system if your querying code is enabling (and presumably also disabling) constraints.
You should also avoid the old-fashioned, non-standard Informix OUTER join notation. Unless you are using an impossibly old version of Informix, you should be using the SQL-92 style of joins.
Your question seems to mention two outer joins, but you only show one in the example query. That, too, is a bit puzzling.
The joining conditions between 'e' and the rest of the tables is:
AND c.crsnum = e.crsnum
AND c.batch_no = e.batch_no
AND d.lect_code= e.lect_code
This is an unusual combination. Since we do not have the relevant subset of the schema with the relevant referential integrity constraints, it is hard to know whether this is correct or not, but it is a little unusual to join between 3 tables like that.
None of this is a definitive answer to you problem; however, it may provide some guidance.
Thank you for all the input made so far. I just wanna add on that while one may have successfully normalized DB, updated any schema changes to their application (e.g. to dataset) or so, there is also another cause: sql CARTESIAN product (when joining tables in queries).
The existence of a cartesian query result will cause duplicate records in the primary (or key first) table of two or more tables being joined.
Even if you specify a "Where" clause in the SQL, a Cartesian may still occur if JOIN with secondary table for example contains the unequal join (useful when to get data from 2 or more UNrelated tables):
FROM tbFirst INNER JOIN
tbSystem ON tbFirst.reference_str <> tbSystem.systemKey_str
Solution for this:
tables should be related.
Thanks. chagbert
I solved the same problem by changing this from false to true. in the end I went into the database and changed my bit field to allow null, and then refreshed my xsd, and refreshed my wsdl and reference.cs and now all is well.
this.columnAttachPDFToEmailFlag.AllowDBNull = true;
Short and easy Soloution:
Go to MSSQL Studio Sever ;
Run the query of the cause of this error : in my case i see that id value was null because i forget to set Identity specification increment by 1.
So entered 1 for the id field as its is autoincremane and modify dont allow NULLS in desing view
That was the error that caused my bindingsource and tabel adapter throwin error at this code:
this.exchangeCheckoutReportTableAdapter.Fill(this.sbmsDataSet.ExchangeCheckouReportTable);
DirectCast(dt.Rows(0),DataRow).RowError
This directly gives the error
If you are using visual studio dataset designer to get the data table, and it is throwing an error 'Failed to Enable constraints'. I've faced the same problem, try to preview the data from the dataset designer itself and match it with table inside your database.
The best way to solve this issue is to delete the table adapter and create a new one instead.
* Secondary way : *
If you don't need [id] to be as Primary key,
Remove its primary key attribute:
on your DataSet > TableAdapter > right click on [id] column > select Delete key ...
Problem will be fixed.
I also had this issue and it was resolved after modifying the *.xsd to reflect the revised size of the column changed in the underlying SQL server.
To fix this error, i took off the troubling table adapter from the Dataset designer, and saved the dataset, and then dragged a fresh copy of the table adapter from the server explorer and that fixed it
I resolved this problem by opening the .xsd file with an XML reader and deleting a constraint placed on one of my views. For whatever reason when I added the view to the data it added a primary key constraint to one of the columns when there shouldn't have been one.
The other way is to open the .xsd file normally, look at the table/view causing the issue and delete any keys (right click column, select delete key) that should not be there.
Just want to add another possible reason for the exception to those listed above (especially for people who like to define dataset schema manually):
when in your dataset you have two tables and there is a relationship (DataSet.Reletions.Add()) defined from first table's field (chfield) to the second table's field (pfield), there is like an implicit constraint is added to that field to be unique even though it may be not specified as such explicitly in your definition neither as unique nor as a primary key.
As a consequence, should you have rows with repetitive values in that parent field (pfield) you'll get this exception too.
In my case this error was provoked by a size of a string column. What was weird was when I executed the exact same query in different tool, repeated values nor null values weren't there.
Then I discovered that the size of a string column size was 50 so when I called the fill method the value was chopped, throwing this exception.
I click on the column and set in the properties the size to 200 and the error was gone.
Hope this help
I solved this problem by doing the "subselect" like it:
string newQuery = "select * from (" + query + ") as temp";
When do it on mysql, all collunms properties (unique, non-null ...) will be cleared.
using (var tbl = new DataTable())
using (var rdr = cmd.ExecuteReader())
{
tbl.BeginLoadData();
try
{
tbl.Load(rdr);
}
catch (ConstraintException ex)
{
rdr.Close();
tbl.Clear();
// clear constraints, source of exceptions
// note: column schema already loaded!
tbl.Constraints.Clear();
tbl.Load(cmd.ExecuteReader());
}
finally
{
tbl.EndLoadData();
}
}
I received the same error type and in my case it solved it by removing the select fields and replacing them with a *. No idea why it was happening. The query had no typos or anything fancy.
Not the best solution but nothing else worked and I was getting exhausted.
In my search for a clear answer I found this on this:
https://www.codeproject.com/questions/45516/failed-to-enable-constraints-one-or-more-rows-cont
Solution 8
This error was also showing in my project, using Visual Studio 2010. I tried other solutions posted in other blogs, but no luck at all because the problem had nothing to do with fields size, table key fields definition, constraints or the EnforceConstraints dataset variable.
In my case I have a .xsd object which I put there during the project design time (in the Data Access Layer). As you drag your database table objects into the Dataset visual item, it reads each table definition from the underlying database and copies the constraints into the Dataset object exactly as you defined them when you created the tables in your database (SQL Server 2008 R2 in my case). This means that every table column created with the constraint of "not null" or "foreign key" must also be present in the result of your SQL statement or stored procedure.
After I included all the constrained columns (not null, primary key, foreign key, etc) into my queries the problem disappeared completely.
Perhaps you don't need all the table columns to be present in the query/stored procedure result, but because the constraints are still applied the error is shown if some constrained column does not appear in the result.
Hope this helps someone else.
If you have failing DataSet (not DataTable):
if (dataSet.HasErrors)
foreach (DataTable table in dataSet.Tables)
if (table.HasErrors)
foreach (var row in table.GetErrors())
Debug.Write($"Error in DataTable {table.TableName}: {row.RowError}")
if _sample_DataSet was the name of dataset that encounter error while filling, you can put the fill dataset inside a Try Catch and then put following code in catch{} block then you are able to exactly find the erroneous column.
foreach (DataTable _dtable in _sample_DataSet.DataSet.Tables)
{
foreach (DataRow dr in _dtable.Rows)
{
if (dr.HasErrors)
{
if (dr.HasErrors)
{
Debug.Write("Row error="+dr.RowError);
}
}
}

How to insert to table with one-to-one relationship via dataset

I use asp.net 4 and DataSets for accessing the database. There are two tables with one-to-one relationship in the database. It means that both tables have the same column as a primary key (say Id), and one of tables has #identity on this column set.
So in general if we want to insert, we insert first into the first table, than insert into the second table with id.table2 = id of the corresponding record in table1.
I can imagine how to achieve this using stored procedure (we would insert into the first table and have id as an out parameter and then insert into the second table using this id, btw all inside one transaction).
But is there a way to do it without using a stored procedure? May be DataSets \ DataAdapters have such functionality built in?
Would appreciate any help.
Today it is so quiet here... Ok if anybody is also looking for such a solution, I've found a way to do it.
So our main problem is to get the id of the newly created record in the first table. If we're able to do that, after that we simply supply it to the next method which creates a corresponding record in the second table.
I used a DataSet Designer in order to enjoy the code autogeneration feature of the VS. Let's call the first table TripSets. In DataSet Designer right click on the TripSetsTableAdapter, then Properties. Expand InsertCommand properties group. Here we need to do two things.
First we add a new parameter into the collection of parameters using the Parameters Collection Editor. Set ParameterName = #TripId, DbType = Int32 (or whatever you need), Direction = Output.
Second we modify the CommandText (using Query Builder for convenience). Add to the end of the command another one after a semicolon like that:
(...);
SELECT #TripId = SCOPE_IDENTITY()
So you will get something like this statement:
INSERT INTO TripSets
(Date, UserId)
VALUES
(#Date,#UserId);
SELECT #TripId = SCOPE_IDENTITY()
Perhaps you will get a parser error warning, but you can just ignore it. Having this configured now we are able to use in our Business logic code as follows:
int tripId;
int result = tripSetsTableAdapter.Insert(tripDate, userId, out tripId);
// Here comes the insert method into the second table
tripSetTripSearchTableAdapter.Insert(tripId, amountPersons);
Probably you will want to synchronize this operations somehow (e.g. using TransactionScope) but it is completely up to you.

VS2005/VS2008 DataSet designer, insert a row into a table that has an autogenerated guid column

I have a strongly typed DataTable created with the VS2005/VS2008 DataSet designer.
The table has a Primary Key column that is a guid, which gets populated by SQL server. The problem is when I want add a row (or multiple rows) to my DataTable and then call the DataAdapter.Update method (passing in the DataTable). When DataAdapter.Update is called I get a SQL exception saying that I cannot insert NULL into the primary key column.
How do I tell the designer that this is an autogenerated column and I do not want to provide a value for new rows? I just want the value generated by SQL.
Am I missing something here, or is this a limitation of the DataSet designer?
I know how achieve this using LINQ to SQL, but unfortunatley I do not have it at my disposal for this project.
Possibly one of these:
If you don't need the column in your DataSet for your app, then remove it.
If you want the column but don't care to give it a value, then change it to allow DBNull.
You can always turn off constraint enforcement (probably a bad idea): DataSet.EnforceConstraints = false
You could fill the column with a surrogate key that does not get sent to the DB.
For the first two options, if you want the convenience of letting the designer keep your structure in sync with your database, then you could remove the column or allow null programmatically, perhaps right next to a "// HACK: " comment explaining why.
You're problably using DEFAULT NEWID() on your SQL Server table definition so the problem may be that the Dataset designer doesn't see this column as auto-generated.
Maybe generating guid in your application code could be a solution? If not, then you could set default value in you Dataset but then you're probably have to also change DataAdapter Insert/Update statements so that this default value doesn't get inserted into Sql Server table.
There could also be some other solution that I'm not aware of...

Categories

Resources