ASP. NET MVC4 + EF4.1 Series II entity Code First

Source: Internet
Author: User

Previously, we have been able to easily create an MVC4 project. Next, we will add a class library to the project. This class library is used to create EF and plays the role of the Model layer in MVC. First, add the "ADO. NET Object Data Model" (I use the Simplified Chinese version). Although it is easy to build, it takes care of beginners.

In this way, EF is created.

As mentioned in the previous article, Code First is started through a small Demo. Use this small example to perform a simple CRUD and first create an object.

1. Create an object

I like EF's graphic design domain structure very much. entity design is like:

It is easy to see that there is a one-to-many relationship between the student score and the score record. A student can have multiple score records because each course has a score record, A course can also be recorded multiple times, so it is not difficult to find that the relationship between students and courses is many-to-many. A student has a pair of courses, of course, a course can also belong to multiple students.

Ii. Writing entities

If the relationship has been clarified, we need to write these entities. The heroes who have used EF may know that EF automatically generates classes in the background as long as you design the entity. But here I do not do this. I will not allow it to be automatically generated. I will change the EF attribute and code generation policy to "NONE", as shown in:

Pay attention to the red lines so that EF will not automatically generate code for us in the background. So everyone will wonder if I want to manually write these classes and relationship mappings. The answer is "NO ". This is the power of Microsoft. We use the T4 template to generate the displayed entity code. First, add the code generation item.

Select ADO. NET DbContext Generrator, that is, the red line option on the graph. You may remember that I mentioned earlier that we will use some new features of EF4.1. It is shown here. The specified object has been generated.
Student Entity:

namespace MVC4School.Model{    using System;    using System.Collections.Generic;        public partial class Student    {        public Student()        {            this.Performance = new HashSet<Performance>();        }            public System.Guid ID { get; set; }        public string FirstName { get; set; }        public string LastName { get; set; }        public string StudentNum { get; set; }        public System.DateTime CreateAt { get; set; }        public string RecordTime { get; set; }            public virtual ICollection<Performance> Performance { get; set; }    }}

It is easy to see that the score record attribute is modified by virtual, indicating that the loading is delayed, which improves the performance. In EF, this virtual is not necessary, without the reference of visual, there will be no error, but it is null. Maybe the comrades who know about nhib.pdf will report an error if they know that this is required in nhib.pdf.

The object code of the score record is as follows:

namespace MVC4School.Model{    using System;    using System.Collections.Generic;        public partial class Performance    {        public System.Guid ID { get; set; }        public string Score { get; set; }        public string CreatAt { get; set; }            public virtual Student Student { get; set; }        public virtual Course Course { get; set; }    }}

The course entity code is as follows:

namespace MVC4School.Model{    using System;    using System.Collections.Generic;        public partial class Course    {        public Course()        {            this.Performance = new HashSet<Performance>();        }            public System.Guid ID { get; set; }        public string Name { get; set; }        public string CreatAt { get; set; }            public virtual ICollection<Performance> Performance { get; set; }    }}

In this way, the code of these three entities is fully presented to us, but we don't need to write a line of code, is it very convenient? (Don't say I'm lazy. Why don't I need a quick way ?)

Iii. creating the Database Context

This class mainly includes the classes created above. It mainly refers to the entities contained in the data model. It also specifies the ing relationship of the created entities and some constraints.

The automatically generated code is as follows:

View Code

 1 namespace MVC4School.Model 2 { 3     using System; 4     using System.Data.Entity; 5     using System.Data.Entity.Infrastructure; 6      7     public partial class SchoolModelContainer : DbContext 8     { 9         public SchoolModelContainer()10             : base("name=SchoolModelContainer")11         {12         }13     14         protected override void OnModelCreating(DbModelBuilder modelBuilder)15         {16             throw new UnintentionalCodeFirstException();17         }18     19         public DbSet<Student> Students { get; set; }20         public DbSet<Course> Courses { get; set; }21         public DbSet<Performance> Performances { get; set; }22     }23 }

Here I will give some simple explanations

        public SchoolModelContainer()            : base("name=SchoolModelContainer")        {        }

"Name = SchoolModelConter" specifies the connection string. The connection string is in the App. config configuration file. When you open this file, you will see the following code:

<?xml version="1.0" encoding="utf-8"?><configuration>  <connectionStrings>    <add name="SchoolModelContainer" connectionString="metadata=res://*/SchoolModel.csdl|res://*/SchoolModel.ssdl|res://*/SchoolModel.msl;provider=System.Data.SqlClient;provider connection string='data source=.\SQLEXPRESS;attachdbfilename="C:\Documents and Settings\Administrator.9682B89E07F644F\My Documents\SchoolModel.mdf";integrated security=True;connect timeout=30;user instance=True;multipleactiveresultsets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />  </connectionStrings></configuration>

This connection string specifies the database type and connection string. I forgot to tell you that EF supports most popular databases.

In this way, the T4 template writes all the code for us. In the next section, I will show you the data initialization and basic CRUD.

To be continued ......

 

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.