Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
7 Reeds Avatar asked Mar 05 '23 04:03

7 Reeds


2 Answers

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);
}
like image 138
Farinaz Avatar answered Mar 12 '23 17:03

Farinaz


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);
 }
like image 26
Chris Catignani Avatar answered Mar 12 '23 16:03

Chris Catignani