Develop your own blog. NET version step by step (9. Replace model first with code first problem records),. netmodel

Source: Internet
Author: User

Develop your own blog. NET version step by step (9. Replace model first with code first problem records),. netmodel
Why use code first instead?

When code first is used, model first or db first is basically no longer used ). Don't ask why I didn't start using code first directly, because at that time I didn't (or even regard model first as code first ).

Because code first is used at work, the more you get used to it, the more you like it.

If:

  • It is no longer urgent to generate the bulky edmx file each time.
  • You no longer have to worry about saving tt files and losing features, deregistering, and scaling methods.
  • You no longer have to write Metadata files to use the Microsoft verification plug-in.
  • You no longer need to write (partial) partial classes to extend the object classes generated by tt files.
  • You no longer need to modify the syntax code in the pitfall tt files to generate objects that meet your needs (for example, each object inherits a parent class by default)
  • You no longer need to edit the huge edmx file to find the pitfalls.
  • And so on ....
Change if necessary

Entity before modification: db first (generated by tt file)

Modified entity: code first (fully handwritten)

Then, update the object to the table structure corresponding to the database. Execute the command Enable-Migrations

Problems:

The EntityFramework package is not installed on project ''. (cause:" Default project "is not selected ")

Continue:

 

The project 'blogs. model' failed to build. (cause: no class inherited from DbContext is created)

 

OK. The migration is enabled.

Then we execute the command: Add-Migration blogs

Exception: An error occurred while obtaining the provider information from the database. This may be caused by incorrect connection strings used by Entity Framework. For more information, see internal exceptions and ensure that the connection string is correct.

My dear friend, I am very sure that our string link is correct.

Finally, make sure you forget to pass the database connection name of the configuration file to the data connection context in the constructor.

  public BlogDbContext()            : base("HiBlogsTest")        {        }

 

Execute (Add-Migration blogs) again, and then make an error:

 

Exception: the specified metadata resource cannot be loaded. (Baidu, it turns out that there is a problem with the link string. Http://www.cnblogs.com/chengxiaohui/articles/2106765.html)

 <add name="HiBlogsTest" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;         provider connection string=&quot;         data source=.;         initial catalog=HiBlogsTest;         user id=sa;         password=123qwe;         MultipleActiveResultSets=True;         App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

 

Change to: (leave a simple link for a bunch of csdl, ssdl, and msl. Clean)

<add name="HiBlogsTest" connectionString="Data Source=.;Initial Catalog=HiBlogsTest;User ID=sa;Password=123qwe;" providerName="System.Data.SqlClient" />

 

OK. I finally don't see the red word.

An automatically generated blogs file is displayed. Check whether the database has a table structure.

Empty. (Nothing can be seen in the fart) (cause: No entity is added in the context of BlogDbContext, and no entity to be generated by the program is told to the database)

Add data code to the BlogDbContext class:

  public class BlogDbContext : DbContext    {        public BlogDbContext()            : base("HiBlogsTest")        {        }               public DbSet<BlogInfo> BlogInfos { get; set; }        public DbSet<BlogComment> BlogComments { get; set; }        public DbSet<BlogReadInfo> BlogReadInfos { get; set; }        public DbSet<BlogTag> BlogTags { get; set; }        public DbSet<BlogType> BlogTypes { get; set; }        public DbSet<BlogUser> BlogUsers { get; set; }        public DbSet<BlogUserInfo> BlogUserInfos { get; set; }    }

 

Run Add-Migration blogs and then update-database.

Finally, we can see the table data.

The table does not work. We do not have a primary or foreign key.

Modify BlogDbContext as follows:

Public class BlogDbContext: DbContext {public BlogDbContext (): base ("HiBlogsTest") {} protected override void OnModelCreating (DbModelBuilder modelBuilder) {base. onModelCreating (modelBuilder); var entityBlogUser = modelBuilder. entity <BlogUser> (); entityBlogUser. hasMany (p => p. blogInfos ). withRequired (t => t. blogUser ). map (m => m. mapKey ("BlogUserId"); entityBlogUser. hasRequired (p => p. blogUserInfo ). withRequiredPrincipal (t => t. blogUser ). map (m => m. mapKey ("BlogUserId"); entityBlogUser. hasMany (p => p. blogTags ). withRequired (t => t. blogUser ). map (m => m. mapKey ("BlogUserId"); entityBlogUser. hasMany (p => p. blogTypes ). withRequired (t => t. blogUser ). map (m => m. mapKey ("BlogUserId"); entityBlogUser. hasMany (p => p. blogComments ). withRequired (t => t. blogUser ). map (m => m. mapKey ("BlogUserId"); var entityBlogInfo = modelBuilder. entity <BlogInfo> (); entityBlogInfo. hasMany (p => p. blogTags ). withiterator (t => t. blogInfos ). map (m => m. toTable ("BlogInfo_BlogTag"); entityBlogInfo. hasMany (p => p. blogTypes ). withiterator (t => t. blogInfos ). map (m => m. toTable ("BlogInfo_BlogType"); entityBlogInfo. hasMany (p => p. blogComments ). withRequired (t => t. blogInfo ). map (m => m. mapKey ("BlogInfoId"); entityBlogInfo. hasMany (p => p. blogReadInfos ). withRequired (t => t. blogInfo ). map (m => m. mapKey ("BlogInfoId");} public DbSet <BlogInfo> BlogInfos {get; set;} public DbSet <BlogComment> BlogComments {get; set ;} public DbSet <BlogReadInfo> BlogReadInfos {get; set;} public DbSet <BlogTag> BlogTags {get; set;} public DbSet <BlogType> BlogTypes {get; set ;} public DbSet <BlogUser> BlogUsers {get; set;} public DbSet <BlogUserInfo> BlogUserInfos {get; set ;}}View Code

 

Run the "Add-Migration blogs" command again and then run the "update-database" command.

See the error again:

The foreign key constraint 'fk _ dbo. bloginfo_dbo.bloguser_bloguserid' is introduced into the 'bloginfo' table, which may cause loops or multiple cascade paths. Specify on delete no action or on update no action, or modify other foreign key constraints.
The constraint cannot be created. See the preceding error message.

As a result, foreign keys are deleted one by one and created one by one. Finally, we found that: (Database relational diagram, generated by mssql)

Baidu: (originally used to restrict cascading deletion of data. To be honest, you haven't played cascade deletion yet, which means this requirement should not be very common. Can I find a method to disable it ?)

Add a. WillCascadeOnDelete (false) directly. Http://www.cnblogs.com/chear/archive/2012/11/09/2762145.html)

Public class BlogDbContext: DbContext {public BlogDbContext (): base ("HiBlogsTest") {} protected override void OnModelCreating (DbModelBuilder modelBuilder) {base. onModelCreating (modelBuilder); var entityBlogUser = modelBuilder. entity <BlogUser> (); entityBlogUser. hasMany (p => p. blogInfos ). withRequired (t => t. blogUser ). map (m => m. mapKey ("BlogUserId ")). willCascadeOnDelete (false); // equivalent to the above // modelBuilder. entity <BlogInfo> (). hasRequired (p => p. blogUser ). withiterator (t => t. blogInfos) // uses the BlogUser as the primary table (BlogUserInfo as the slave table and creates a foreign key) entityBlogUser. hasRequired (p => p. blogUserInfo ). withRequiredPrincipal (t => t. blogUser ). map (m => m. mapKey ("BlogUserId ")). willCascadeOnDelete (false); // equivalent to HasRequired (p => ). witexceptional (I =>); // use BlogUserInfo as the main table (BlogUser is the slave table and a foreign key is created) // modelBuilder. entity <BlogUser> (). hasRequired (p => p. blogUserInfo ). withRequiredDependent (t => t. blogUser )//. map (m => m. mapKey ("BlogUserId ")). willCascadeOnDelete (false); // equivalent to HasOptional (p => ). withRequired (I =>); entityBlogUser. hasMany (p => p. blogTags ). withRequired (t => t. blogUser ). map (m => m. mapKey ("BlogUserId ")). willCascadeOnDelete (false); entityBlogUser. hasMany (p => p. blogTypes ). withRequired (t => t. blogUser ). map (m => m. mapKey ("BlogUserId ")). willCascadeOnDelete (false); entityBlogUser. hasMany (p => p. blogComments ). withRequired (t => t. blogUser ). map (m => m. mapKey ("BlogUserId ")). willCascadeOnDelete (false); var entityBlogInfo = modelBuilder. entity <BlogInfo> (); entityBlogInfo. hasMany (p => p. blogTags ). withiterator (t => t. blogInfos ). map (m => m. toTable ("BlogInfo_BlogTag"); entityBlogInfo. hasMany (p => p. blogTypes ). withiterator (t => t. blogInfos ). map (m => m. toTable ("BlogInfo_BlogType"); entityBlogInfo. hasMany (p => p. blogComments ). withRequired (t => t. blogInfo ). map (m => m. mapKey ("BlogInfoId ")). willCascadeOnDelete (false); entityBlogInfo. hasMany (p => p. blogReadInfos ). withRequired (t => t. blogInfo ). map (m => m. mapKey ("BlogInfoId ")). willCascadeOnDelete (false);} public DbSet <BlogInfo> BlogInfos {get; set;} public DbSet <BlogComment> BlogComments {get; set;} public DbSet <BlogReadInfo> BlogReadInfos {get; set;} public DbSet <BlogTag> BlogTags {get; set;} public DbSet <BlogType> BlogTypes {get; set;} public DbSet <BlogUser> BlogUsers {get; set ;} public DbSet <BlogUserInfo> BlogUserInfos {get; set ;}}View Code

 

Run the "Add-Migration blogs" command again and then run the "update-database" command.

Perfect. The table structure is over. The table relationship has arrived. (The following code is used. Because the table name has been slightly changed and the field has been slightly adjusted, there are quite a few changes. A whole day has been rectified .)

Now let's look back and think about the db first that was used after model first was slightly changed. I have never encountered this problem before (adding the FOREIGN KEY constraint 'fk _ dbo. bloginfo_dbo.bloguser_bloguserid' to the table 'bloginfo' may cause loops or multiple cascade paths. Specify on delete no action or on update no action, or modify other foreign key constraints.
The constraint cannot be created. See previous error messages .) This error occurs. Driven by curiosity, I feel that I can see how edmx of the previous Code manages this relationship.

I was surprised to find that there was no problem at all. So, let's see if there are any flaws in the database.

Search for shards. By default, the primary and foreign key relationships generated through model first are not designed for cascading deletion, and the default setting of code first is cascading deletion.

 

I am talking nonsense about the above content. Thank you for reading this article. I hope it will help you a little bit.

Hi-Blogs Source Code address: http://git.oschina.net/zhaopeiym/Hi-Blogs

Recently, open-source blogs have not been updated for a long time because their work has been too slow. Today, I suddenly went back and forth several times and found that the code I wrote six months ago was so unsightly.

Today, I only changed db first to code first. I have to find time to refactor the moldy code.

Starting address: http://www.cnblogs.com/zhaopei/p/5540532.html

 

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.