Entity Framework knowledge sharing, entityframework

Source: Internet
Author: User

Entity Framework knowledge sharing, entityframework

Reference page:

Http://www.yuanjiaocheng.net/entity/Persistence-in-EF.html

Http://www.yuanjiaocheng.net/entity/crud-in-connected.html

Http://www.yuanjiaocheng.net/entity/crud-in-Disconnected.html

Http://www.yuanjiaocheng.net/entity/add-entity-in-disconnected.html

Http://www.yuanjiaocheng.net/entity/update-entity.html

The days with Entity Framework are painful and happy. Today, I will share with you a happy and painful experience.

Happy first. When the Entity Framework inserts data into the database, if the primary key field is an auto-incrementing ID column, the auto-increment value is returned to the corresponding attribute of the object.

For example, the following sample code adds a blog to the database:

Var blogPost = new BlogPost ()
{
Author = "blog Garden ",
Title = "programmer's online home"
};
Using (BlogDbContext context = new BlogDbContext ())
{
Context. BlogPosts. Add (blogPost );
Context. SaveChanges ();
Return blogPost. ID;
}

After SaveChanges (), the value of blogPost. ID is the value of the auto-increment ID column in the database.

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

Exec sp_executesql n' insert [dbo]. [blog_Content] ([Title], [Author])
Values (@ 0, @ 1)
Select [ID]
From [dbo]. [blog_Content]
Where @ ROWCOUNT> 0 and [ID] = scope_identity ()',
N' @ 0 nvarchar (128), @ 1 nvarchar (128), ', @ 0 = n' programmer's online home', @ 1 = n' blog Garden'

EF obtains the value of the auto-increment column through scope_identity (), and does not set the ID attribute of BlogPost. EF intelligently determines that the ID is the auto-increment ID column.

In the past, when Entity Framework was not used, stored procedures were used. Stored Procedures had a bunch of parameters, and attribute values of object objects were assigned to these parameters one by one. After the stored procedure was executed, it also uses ParameterDirection. the Output parameter obtains the value of the auto-increment ID.

Now, you just need to give something to the Entity Framework and tell her to put it in the database. Worry-free! So happy!

However, the self-righteous Entity Framework uses this feature to make people happy, but it also brings a little pain to people. She believes that as long as the entity class has the ID attribute, the database must correspond to the auto-incrementing ID column, which is really self-righteous. After adding a blog to the database, we are going to use this auto-increment ID to add the content to the database. (The content is stored in a separate database and associated with the content through the ID field, but an error message is displayed:

Cannot insert the value NULL into column 'id', table 'cnblogstext. dbo. blog_PostBody '; column does not allow nulls.

Look at the SQL statements generated by EF:

Exec sp_executesql n' insert [dbo]. [CNBlogsText_blog_PostBody] ([Text])
Values (@ 0)
Select [ID]
From [dbo]. [CNBlogsText_blog_PostBody]
Where @ ROWCOUNT> 0 and [ID] = scope_identity () ', n' @ 0 nvarchar (128)', @ 0 = n' help programmers change the world with technology'

It is not an auto-increment column, but also scope_identity (). Such a clever Entity Framework will also do such silly things.

Fortunately, the flexibility of EF customization makes it easy for us to resolve this pain, as long as the following code is added to BlogDbContext:

Protected override void OnModelCreating (DbModelBuilder modelBuilder)
{
ModelBuilder. Entity <PostBody> (). Property (p => p. ID)
. HasDatabaseGeneratedOption (DatabaseGeneratedOption. None );
}

You can also add tags to object attributes:

 

Public class BlogPost
{
[DatabaseGenerated (DatabaseGeneratedOption. None)]
Public int ID {get; set ;}
}

The second pain point is that the well-known Entity Framework does not support enumeration types. Although we all know it, we still want to get it out and get rid of it.

 

How does EF deal with enumeration types? EF turns a blind eye to the enumeration type attributes that actually exist in the object class when they do not exist.

This pain cannot be solved at present (to wait for the next version of EF). You can only use the left-side path to relieve the pain. Please refer to the "left-side path" and "Garden ".

Code in the object class:

Public class BlogPost
{
Public BlogPostType PostType
{
Get {return (BlogPostType) PostTypeEf ;}
Set {PostTypeEf = (int) value ;}
}
Public int PostTypeEf {get; set ;}
}

EF does not recognize the enumeration type, but int type. Therefore, a PostTypeEf is added, which is only used for EF purposes. If EF supports the enumeration type in the next version, remove it.

BlogDbContext must also be modified in combination:

Protected override void OnModelCreating (DbModelBuilder modelBuilder)
{
ModelBuilder. Entity <BlogPost> (). Ignore (p => p. PostConfig );
ModelBuilder. Entity <BlogPost> (). Property (p => p. PostTypeEf)
. HasColumnName ("PostType ");
}

After sharing, you will be happier and more painful.

Related Article

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.