I have a table of phone numbers that comes from a DB model. The table has a primary key phoneId
with an "autoincrement" value. I need to insert a new row but the model version of the table does not have a nullable phoneId
member. How do I specify that the new record should get the next autoincrement/identity number?
I am trying:
var newPhone = new Phone() {
PhoneId = null,
PhoneNumber = newNumber
};
try {
pdb.Phones.Add(newPhone);
pdb.SaveChanges();
} catch (Exception e) {
Console.WriteLine("COULD NOT ADD new number: {0}", e.Message);
}
in the model PhoneId
is a "long" not a "long?". I don't want to change the model if I don't have to. If I ever rebuild the model I will lose the change and will probably forget why I needed it.
I tried duplicating the model Phone
class and setting that version of the PhoneId
to nullable but then the Linq .Add()
method balked because it could not convert one to the other.
What am I missing?
You do not have to set the field, The field is initialized when you submit the model
var newPhone = new Phone() {
PhoneNumber = newNumber
};
try {
pdb.Phones.Add(newPhone);
pdb.SaveChanges();
} catch (Exception e) {
Console.WriteLine("COULD NOT ADD new number: {0}", e.Message);
}
The model doesn't have a phoneID because the database will set the value when you insert the record. The primary key cant be nullable also.
More about Identity fields
Look at Example A: in the link above...you will see that they leave out the IDENTITY field.
var newPhone = new Phone();
newPhone.PhoneNumber = newNumber;
try
{
pdb.Phones.Add(newPhone);
pdb.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine("COULD NOT ADD new number: {0}", e.Message);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With