ASP. net mvc -- CodeFirst development mode, mvccodefirst

Source: Internet
Author: User

ASP. net mvc -- CodeFirst development mode, mvccodefirst

The Entity Framework provides several development modes, such as Database First, Model First, and Code First. Database First is the oldest and most widely used design method. The design of Database First is highly dependent on the structure of tables in the Database. The model is created based on the relationship between tables and tables. If the demand changes or the function changes significantly in the future, the price required to change the database will be high, because the Code previously compiled will no longer apply to new tables, we must refactor to change the logic in the code to adapt to the modified table. Model First is to create an ADO. NET object and the relationship between them, and then specify the ing to the database. This object is a Model.

We are going to talk about Code First today ). The idea is to first define the classes in the model and then generate a database through these classes. This development mode is suitable for all-new projects. It allows us to design with code as the core rather than constructing a database first.

Next I will introduce this development mode with a simple example. We need two tables: blog table and comment table. One blog corresponds to multiple comments, and one comment corresponds to one blog. This is a one-to-multiple relationship. Create an ASP. net mvc project and install EntityFramework with NuGet. Create two models.

    public class Blog    {        [Key]        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]        public Guid Id { get; set; }        public string Title { get; set; }        public string Author { get; set; }        public DateTime Time { get; set; }        public string Summary { get; set; }        public string Content { get; set; }        public virtual ICollection<Comment> Comments { get; set; } = new List<Comment>();    }
    public class Comment    {        [Key]        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]        public Guid Id { get; set; }        public string VisitorName { get; set; }        public string Email { get; set; }        public DateTime Time { get; set; }        public string Content { get; set; }        [ForeignKey("Blog")]        public Guid BlogId { get; set; }        public virtual Blog Blog { get; set; }    }

Next, we will create a data context. Create a folder named Context and create a class in it. The Code is as follows:

Public class EFDbContext: DbContext {public DbSet <Blog> Blogs {get; set;} public DbSet <Comment> Comments {get; set;} protected override void OnModelCreating (DbModelBuilder modelBuilder) {modelBuilder. conventions. remove <PluralizingTableNameConvention> (); // Remove the Convention "set the table name to the plural }}

Then we configure the database in Web. config. We use the lightweight LocalDB. Add the following configuration to the <configuration> node in Web. config:

  <connectionStrings>    <add name="EFDbContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Blog;Integrated Security=True" providerName="System.Data.SqlClient" />  </connectionStrings>

Next, we create a new controller and select "MVC5 controller containing the view (using Entity Framework)". Because we focus on CodeFirst, we use templates to generate controllers and views, select "Blog" for the model class, and select "EFDbContext" for the data context class. The Controller name is HomeController. Click "add" to add the Controller and View with the CRUD function.

Run the project to perform the CRUD operation. After debugging, open the server resource manager and view the database table generated by code in the data connection.

Finally, let's talk about the relationship between tables. There are three types of relationships: one-to-one, one-to-multiple, and many-to-many. We mainly configure the navigation attributes, such as the previous blog table and comment table. We added such code in the class.

Public virtual ICollection <Comment> Comments {get; set ;}= new List <Comment> (); // one blog corresponds to multiple Comments
Public virtual Blog {get; set;} // a comment corresponds to a blog

We need to use the third table to link to the multi-to-Multi-relationship.

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.