Free Code Snippets in C#, Net Framework, Office 365, ASP.Net,WPF, Visual Studio, SQL Server, Antivirus free
#

 

 

Question:

How do you get the new ID of a record that you attach to a table in SQL Server using EF Entity Framework?

 

Solution:

You create a blank record from the appropriate MVC data model, fill it with new values ​​and default values.

Then you add this to the EF.Table

And then update the EF dbContext.

Then the record has automatically assigned the new ID.

NoteModel note= new NoteModel();

note.DtCreated = DateTime.Now;

await _dbContext.tbl_Notes.AddAsync(note); //IDNote: 0->-99999

await _dbContext.SaveChangesAsync();       //IDNote: -99999->16

 

newID = note.IDNote;

 

Explanation:

At the time of creating new record, the included ID is always 0.

NoteModel note= new NoteModel();

//ID==0

 

Once you get the data

If the record is appended to Entity Framework dbContext, the record is internally set to a temporary ID.

await _dbContext.tbl_Notes.AddAsync(note); //IDNote: 0->-99999

 

By updating EF to SQL Server, the temporary number becomes a real ID, which is automatically incremented by SQL Server for incremental identity.

await _dbContext.SaveChangesAsync();       //IDNote: -99999->16

 

Since the dataset is still local in memory, you can read and process it directly from the dataset

newID = note.IDNote;

 

 

In the debugger

Record is added to EF table.

Before appending, the ID = 0

 

After dbContext.tbl.Add (recordset)

After attaching to the EF dbContext table, the ID is a negative number of type long

 

After performing dbContext.SaveChanges (), the ID becomes the correct ID of the SQL Server

 

 

Complete c # code example

Asp.Net Core 2 MVC

NoteModel note;

if (IDNote==0)

{

    note = _dbContext.tbl_Notes.SingleOrDefault(n => n.IDUser == IDCurrent_User && n.IsDraft==true);

    if (note == null)

    {

        note = new NoteModel();

        note.IsDraft = true;

        note.DtCreated = DateTime.Now;

        note.IDUser = IDCurrent_User;

        note.Title = "#images";

        note.sumImages = 0;

        note.DtEdit = DateTime.Now;

 

        //< save >

        await _dbContext.tbl_Notes.AddAsync(note); //IDNote: 0->-99999

        await _dbContext.SaveChangesAsync();       //IDNote: -99999->16

        //</ save >

 

        //< new ID >

        IDNote = note.IDNote;

        //Console.WriteLine("new IDNote=" + note.IDNote);

        //</ new ID >

    }

    else

    {

        //< last draft >

        IDNote = note.IDNote;

        //</ last draft >

    }

}

 

Mobile
»
EF: Determine new ID of a data record
»
Asp MVC: Output Data from SQL Server directly to a List Type
»
Linq: Query data with a left join
»
Asp Linq: Collect data with a LINQ query from SQL Server

.

Contact for Jobs, Project Requests: raimund.popp@microsoft-programmierer.de