I have 4 tables, IndividualTruck, TruckModel, TruckFeature and TruckFeatureAssociation.
IndividualTruck has a property TruckModel of Type TruckModel. After assigning other properties retrieved from a WPF form, I create the relationship and add these new records into the relevant tables shown below.
IndividualTruck truck = new IndividualTruck();
truck.Colour = Colour; #various other attributes
TruckModel model = new TruckModel();
model.Manufacturer = new Manufacturer; #various other attributes
truck.TruckModel = model; #creating the relationship
#this function checks adds the new truck and saves the table
DAO.AddNewTruck(truck, true);
TruckFeature
table class has int FeatureID
, string Description
and TruckFeatureAssociation : ICollection<TruckFeatureAssociation>
TruckFeatureAssociation
table class has int TruckID
, int FeatureID
, Feature: TruckFeature
and Truck: IndividualTruck
.
I have a list box where multiple features can be selected out of the table TruckFeature
, it's a table with four entries (Air conditioning, Rear door for loading, alarms system and keyless door).
I've attempted to loop through the list of selected features and retrieve the FeatureID
of those selected to assign to assign the featureID
to the association table which is two columns TruckID
and FeatureID
both primary keys.
When I go to save the data to the tables, I get a SQL error
SqlException: Cannot insert explicit value for identity column in table 'TruckFeature' when IDENTITY_INSERT is set to OFF.
Cannot insert explicit value as insert is OFF
How do I create this relationship without changing this insert OFF condition? TIA. Sorry for the messy question I'm REALLY new to .NET and C#.
UPDATE:
for (int i = featureListBox.SelectedItems.Count - 1; i >= 0; --i)
{
TruckFeatureAssociation association = new TruckFeatureAssociation();
TruckFeature truckFeature = new TruckFeature();
string feature = featureListBox.SelectedItems[i].ToString();
truckFeature = DAO.SearchBySelected(feature);
association.Feature = truckFeature;
association.Truck = truck;
DAO.addNewFeatureAssc(association);
}
and
public static void addNewFeatureAssc(TruckFeatureAssociation ff)
{
using (DAD_BaldipContext ctx = new DAD_BaldipContext())
{
ctx.TruckFeatureAssociation.Add(ff);
ctx.SaveChanges();
}
}
The error shows up next to ctx.savechanges();