Tuesday, March 27, 2012

DataTable and autoincremental Database Fields

Hi,

I got a problem regarding autoincremental Database Fields and DataTables. Using the technique to map the DataBase to an *.xsd file and trying to insert a Row into the table always results in this kind of error:

Cannot insert explicit value for identity column in table 'Cars' when IDENTITY_INSERT is set to OFF.

This only happens when I set CarIDs properties AutoIncrement = true, AutoIncrementSeed = -1, AutoIncrementStep = -1. Having AutoIncrement = false, results in this error:

Column 'CarID' does not allow nulls.
Do I missunderstand something, or do I need to change some parts? I would be glad if someone could help me and figure out what I am doing wrong.
Thanks a lot have a nice weekend.
Regards Johannes

Hi,

i figured out something new. Regarding the line in which the error occurs it happens when I am trying to add a new row into the Datatable.

That's my code:

1[System.ComponentModel.DataObjectMethodAttribute2 (System.ComponentModel.DataObjectMethodType.Insert,true)]3public bool InsertCar(int CarType,string CarNumberPlate,string CarMileage,4string CarServiceRange,bool CarSummerTires,bool CarWinterTires,bool CarHitch,5int CarCarageID, Guid CarUserID, DateTime CarPurchased,bool CarSold)6 {7 Fleet.CarsDataTable cars =new Fleet.CarsDataTable();8 Fleet.CarsRow car = cars.NewCarsRow();91011 car.CarType = CarType;12 car.CarNumberPlate = CarNumberPlate;13 car.CarMileage = CarMileage;14 car.CarServiceRange = CarServiceRange;15 car.CarSummerTires = CarSummerTires;16 car.CarWinterTires = CarWinterTires;17 car.CarHitch = CarHitch;18 car.CarGarageID = CarCarageID;19 car.CarUserID = CarUserID;20 car.CarPurchased = CarPurchased;21 car.CarSold = CarSold;2223 cars.AddCarsRow(car);24int rowsAffected = Adapter.Update(cars);2526return rowsAffected == 1;27 }

The error occurs in line 23. Depeding on the settings in my Fleed.xsd file for CarID, as mentioned above the error changes.

Okay tried something else and fixed it. I reconfigured my TableAdapter and activatedRefresh the data table.No it works perfectly. Ig anyone could explain that to me I would be happy.

Thanks a lot.

Regards Johannes