Search code examples
c#.netlinqlinq-to-entities

C# .Net Linq adding new record with identity field


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?


Solution

  • 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);
    }