ADO.NET CommandBuilder, InsertCommand and Default Constraints

佐手、 提交于 2019-12-05 12:30:20

You do not need to use a CommandBuilder to implement the update method for your DataAdapter. The CommandBuilder is full of issues. You can set the DataAdapter.SelectCommand and the DataAdapter.UpdateCommand properties to DbCommand objects that specify the sql directly. This avoids the problems inherent in the CommandBuilder's ability to generate proper sql statements.

Update:

There is no way for the CommandBuilder to know that you want to use the default value. All it does is generate an insert statement, if there is a column it is going to generate it for the insert statement. If that column is part of the insert statement, then any value given for that column, even null, will be inserted. The default value is for situations where you do not include it in the insert statement. It does not convert null into the default value, no matter how you try to insert the items, CommandBuilder or not.

Continuing down this path of trying to use the CommandBuilder is only going to give you more grief. It can't even handle a simple join statement in its select clause. It also requires a primary key. If either of these are violated then it cannot generate correct update, insert, and delete statements. Only two providers, Sql Server and Oracle, have ever implemented this class, and the Oracle one is known to have bugs that were never fixed outside of the basic problems mentioned above.

If you used two DbCommand objects, one for selecting and one for inserting, and then looped through the output of the select DbCommand via a DbDataReader, you could easily check for null in that column and provide the default value of zero to the insert DbCommand, since you know what it is. Knowing the rules of the database and using them when necessary is not a violation of any kind of code organization rules. You have to know what is in the database anyways in order to write this kind of code.

If you have sql server 2005 or up, another suggestion is to use the INSERT INTO .. SELECT statement. If your sql is good enough you can use a CASE clause to make a single sql statement.

A little question, it may seem obvious, but in fact it's tricky.

_sqlCommandBuilder.ConflictOption = ConflictOption.OverwriteChanges;

If I quote MSDN definition you may read :

"If no PrimaryKey is defined, all searchable columns are included in the WHERE clause."

A friend of mine, used to define IDENTITY(1, 1) in some camses instead of Primary keys.

So little question is, do you use primary key in your "updated" table B ??



then....

To add informations, SqlAdapter.FillSchema does not use default values Here are informations retrieved by FillSchema :

AllowDBNull 
AutoIncrement.You must set AutoIncrementStep and AutoIncrementSeed separately.
MaxLength 
ReadOnly 
Unique

(Quote from MSDN site)

Unique

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!