简体   繁体   中英

How does Entity Framework insert new values?

I have another question kind of relative to this but I'd like to separate them for clarity reasons.

I stumbled upon a problem where I couldn't insert a new row in a table because it only had one column and that column was incrementally increased and PK.

However, creating a new object of that Set in Entity Framework was no trouble at all.

var admin = new Administrator {};
context.Administrator.AddObject(admin);
context.SaveChanges();
int adminId = admin.adminId; //This would give me the new value

How does this work?

When you commit your changes, Entity Framework performs an INSERT into the table associated with the Administrator entity set, for each added entities. As the PK is auto incremented in the database, EF knows that it doesn't need to provide it, but retreive it after the INSERT. It then updates the Administrator entity with it's now available (and database generated) PK.

It's classic Object relational Mapping job, I hope I understood your question?

Here is the exact SQL query sent by EF to do the Insert job.

insert [dbo].[Entities] default values
select [Id]
  from [dbo].[Entities]
  where @@ROWCOUNT > 0 and [Id] = scope_identity()

It inserts a default row in the table, then select the new row's Id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM