Simple Code First example (EF Code-First series), efcode-first

Source: Internet
Author: User

Simple Code First example (EF Code-First series), efcode-first

Now imagine that we want to create an application for Yingge School, which needs to be able to add or update students, scores, teachers, and course information.

Instead of the previous practice: first, create a database. Now, we will not do this. First, create a domain class. First, I will create two simple classes. One is the Student class, one is the Standard class.

Each student has a score. Let's look at the code below:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF1{   public class Student    {        public int StudentId { get; set; }        public string StudentName { get; set; }        public DateTime DateOfBirth { get; set; }        public byte[] Photo { get; set; }        public decimal Height { get; set; }        public float Weight { get; set; }        public Standard Standard { get; set; }    }}

This Standard (score class) needs to accommodate the next plural Student (Student)

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace EF1{   public class Standard    {       public int StandardId { get; set; }       public string StandardName { get; set; }       public ICollection<Student> Students { get; set; }    }}

Now, we have completed the initialization of the domain class for our program. The Code-First method also requires a context class inherited from DbContext. For more information about the context class, click DbContext.

 

The code for creating a context class is as follows. This context class inherits from the DbContext class, and then exposes the DbSet attributes of the model entity you want, such as Student and Standard classes, in this example. DbSet is the set of objects (also konw as entity set). Therefore, the attribute name of this object is a plural number.

using System;using System.Collections.Generic;using System.Data.Entity;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF1{   public class DbContextClass:DbContext    {       public DbContextClass()           : base()       { }       public DbSet<Student> Studnets { get; set; }       public DbSet<Standard> Standards { get; set; }    }}

Now we have created a required domain class and context class. Now let's use context to add a student information.

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace EF1 {class Program {static void Main (string [] args) {Student stu = new Student () {StudentId = 1, StudentName = "Wei xiaobao", Height = 172, weight = 120, DateOfBirth = DateTime. now}; using (var db = new DbContextClass () {db. studnets. add (stu); db. saveChanges ();} Console. writeLine ("successfully added"); Console. readKey ();}}}

Running:

Succeeded? So you will be surprised. What about databases and data tables:

This is the beauty of Code-First APIs of Entity Framework. it creates the database based on parameter passed in the base constructor of your context class. since we have not passed any parameter in the constructor of our context class, it created "EF_Code_First_Tutorials.SchoolContext" database in the local SQLEXPRESS database, as shown below. it also created two tables in this database, Students and Standards tables based on Student and Standard domain classes defined above.

This is the advantage of Code-First APIs. It creates a database for US based on the parameters in the base constructor in the context class. Although we didn't pass any parameters to the constructor, it created this database for [C: \ Users \ XXXXXX] in this directory:

Note: Because my database version is not a free version, the created database is in the following directory: [C: \ Users \ XXXXXX]

Now I want to append this database to My SQL to view the tables in it, but an error occurred:

The version is not supported. The version of my database is SQL2008. The version of this database should be lower than 2008.

 

On the internet Baidu a bit: solution address: http://www.2cto.com/database/201404/294024.html

"The database version is 661 and cannot be opened. This server supports both version 655 and earlier. The downgrade path is not supported"

This problem is generally caused by different database versions.

We can use the following statement to query the database version.

Use master

Select@ VERSION

(1) 661 is the version number of sql2008 R2

Microsoft SQL Server 2008 R2 (RTM)-10.50.1600.1 (Intel X86) Apr 2010 15:53:02 Copyright (c) Microsoft

(2) version 655, that is, sql2008 sp1 version

Microsoft SQL Server 2008 (SP1)-10.0.2531.0 (Intel X86) Mar 29 2009 10:27:29 Copyright (c) 1988-2008

 

If it is later than 1600, it indicates that only sql2008r2 is installed, and a sql2008sp1 is also installed. In this way, we can ensure that 2500 is followed.

My database is the first version. I am looking for a SQL2008Sp1.

This still does not work. You need to install SQL2012 ......

 

I am too lazy to install SQL2012. Since this method is not feasible, I think of his method. Now let's modify it. The context class:

using System;using System.Collections.Generic;using System.Data.Entity;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF1{   public class DbContextClass:DbContext    {       public DbContextClass()           : base("ConnectionString")       { }       public DbSet<Student> Studnets { get; set; }       public DbSet<Standard> Standards { get; set; }    }}

Then, add the node to the configuration file:

 <connectionStrings>    <add name="ConnectionString" connectionString="server=.;database=EFCodeFirstDB;uid=sa;pwd=Password_1" providerName="System.Data.SqlClient"/>  </connectionStrings>

After running the program, open the database. Miracle!

The database is generated. In SQL2008:

Then let's open the table, and the field is:

 

As you can see in the above figure, it has created Students and Standards tables and each table contains columns with appropriate datatype and length. the column names and datatype matches with the properties of the respective domain classes. it has also made StudentId and StandardId as PK (primary key) and Standard_StandardId column as FK (foreign key ).

This way, without creating a database first, you can start writing an application that will eventually create the database from your domain classes.

You must be wondering how it has created columns with appropriate datatypes and lengh with PK & FK, right? The answer is, using code-first conventions.

Learn code-first conventions in the next section.

 

You can see that in the above figure, the database and table are created, and there is a primary foreign key. These are all implemented by Code-First conventions.

 

Attached series directory:

  • What is Code First?
  • Simple Code First example
  • Code-First Convention
  • DB Initialization (Database Initialization)
  • Inheritance Strategy (Inheritance Policy)
  • Configure Domain Classes (configuration Domain class)
  • DataAnnotations (Data annotation)
  • Fluent API
  • Configure One-to-One (Configure a One-to-One relationship)
  • Configure One-to-multiple (Configure One-to-multiple relationships)
  • Configure allow-to-Configure (Configure Many-to-Many relationships)
  • Move deployments (data migration)
  • DB Initialization Strategy (Database Initialization Policy)
  • ... 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.