Get the self-increment ID value when adding records to the Entity framework

Source: Internet
Author: User
Tags rowcount

var m = new your model ();
Db. Your Model.add (m);

Db. SaveChange ();

Response.Write (m.id); Perform. SaveChange () The ID value can be obtained directly after saving.

There is no ID value before saving.

When the Entity Framework inserts data into a database, if the primary key field is an auto-increment identity column, the self-increment is returned to the property corresponding to the entity object.

For example, add the following blog essays to the Database sample code:

var blogpost = new blogpost () {    Author = "Blog Park",    Title = "Web Home for Programmers"};using (blogdbcontext context = new Blogdbcontex T ()) {    context. Blogposts.add (blogpost);                    Context. SaveChanges ();    

After SaveChanges (), the value of Blogpost.id is the value of the corresponding self-increment identity column in the database.

Take a look at the SQL statements generated by the Entity Framework:

1EXEC sp_executesql N'Insert [dbo]. [Blog_content] ([Title],[author])2VALUES (@0, @1)3 Select[ID]4  from[dbo]. [Blog_content]5 where@ @ROWCOUNT >0and [ID] = scope_identity ()',6N'@0 nvarchar, @1 nvarchar (+),',@0=n'online home for programmers',@1=n'Blog Park'
View Code

EF takes the added value from scope_identity (), and we do not have any settings for the blogpost id attribute, which is the EF intelligently determines that the ID is the self-increment identity column.

In a time when the Entity Framework was not used, a stored procedure was used, and the stored procedure had a bunch of parameters, and the attribute values of the entity objects were assigned to those parameters, after the execution of the stored procedure, The value of the self-increment ID is also obtained through the ParameterDirection.Output parameter.

Now, just give the thing to the entity Framework and tell her to put it in the database. How worry! How happy!

However, the self-righteous Entity Framework uses this feature to give people a bit of pain as well as happiness. She thinks that as long as there is an id attribute in the entity class, the database corresponds to the self-increment identity column, which is quite self-righteous. When we add the blog essay to the database, we are ready to add the essay content to the database with this self-increment ID (the essay content is stored in a separate database, is associated with the essay by ID field, not self-increment), but there is an error message:

1 ' ID '  2'CNBlogsText.dbo.blog_PostBody'; Column does not allow nulls.
View Code

Look at the SQL statements generated by EF:

1EXEC sp_executesql N'Insert [dbo]. [Cnblogstext_blog_postbody] ([Text])2VALUES (@0)3 Select[ID]4  from[dbo]. [Cnblogstext_blog_postbody]5 where@ @ROWCOUNT >0and [ID] = scope_identity ()', N'@0nvarchar -)', @0=n'Help programmers change the world with technology'
View Code

Not self-increment, also a scope_identity (). Such a clever entity Framework would do such a foolish thing.

Fortunately, the EF custom flexible features allow us to easily resolve this pain by simply adding the following code to the Blogdbcontext:

protected Override void onmodelcreating (Dbmodelbuilder modelBuilder) {    modelbuilder.entity<PostBody> (). Property (P = p.id)        . Hasdatabasegeneratedoption (Databasegeneratedoption.none); }

can also be implemented by tagging on entity class properties:

 Public class blogpost{    [databasegenerated (Databasegeneratedoption.none)]    publicint  Getset;}}

The second pain is known as the Entity Framework does not support enumeration types, although we all know, but still want to take out the sun, solution jiehen.

What does EF do with enum types? For attributes of an enumerated type that is actually present in the entity class, EF ignores them as if it does not exist.

For this pain, currently can not be resolved (to wait for the next version of EF), only with the help of the side of the left to alleviate the pain, please see "next to the left side" of the "counter switch".

Code in the entity class:

 Public class blogpost{    public  blogposttype posttype    {        get return  (Blogposttype) Posttypeef; }        set {Posttypeef = (int) value;}    }      Public int Get Set ; }}

EF does not recognize enum types, but it does type int, so add a posttypeef for EF only, and then remove the next version of EF that supports enumeration types.

Get the self-increment ID value when adding records to the Entity framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.