Code First and codefirst

Source: Internet
Author: User
Tags add numbers sql server management studio sql server management studio 2014

Code First and codefirst

I believe everyone is familiar with the code first mode of Entity Framework. This article will look at the usage of Entity inheritance in codefirst.

 

Step 1 Add the code first Environment

For convenience, use VS2013 + SQL server 2014 LocalDb to view data using SQL Server Management Studio 2014

The simplest console is used for the project.

After the console project is created (named EF_CodeFirst_Test), you can use the NuGet interface to add the EF library or use the command to add it.

Enter

Install-Package EntityFramework EF_CodeFirst_Test # Replace it with your own project name

Next, add the connection string to app. config.

<Add name = "CodeFirstModel" connectionString = "data source = (LocalDb) \ MSSQLLocalDb; initial catalog = TestDb; integrated security = True; multipleactiveresultsets = True; application name = EntityFramework "providerName =" System. data. sqlClient "/> <! -- Change to your own database -->
Step 2 Write entity classes

Base type

public class BaseClass{        public long ID { get; set; }        public string Name { get; set; }}

Three extension classes. Annotations are added here to merge some table fields. Otherwise, EF will add numbers such as 1 2 and 3 to the fields with the same name in different subclasses to distinguish them. adding annotations forces different subclasses to use the same field under the same type.

The annotation-related namespaces are as follows:

using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;

Here we want to explain, in. some fields in the Schema in net 4.5 are stored in the built-in class library. net 4 and. net 3.5 is not available. If you use a version to create a project, you can switch to another version..

 

Below are several extension classes

public class ExtendClass:BaseClass{        public string DescriptionString { get; set; }        [Required]        [Column("LongNum")]        public long LongNum { get; set; }}public class ExtendClass2 : BaseClass{        [Column("Version")]        public string Version { get; set; }        [Required]        [Column("IntNum")]        public int IntNum { get; set; }}public class ExtendClass3 : BaseClass{        [Column("Version")]        public string Version { get; set; }        [Required]        [Column("IntNum")]        public int IntNum { get; set; }        [Required]        [Column("LongNum")]        public long LongNum { get; set; }}

 

Finally, the database Context

public partial class CodeFirstModel : DbContext{        public CodeFirstModel()            : base("name=CodeFirstModel")        {        }        public virtual DbSet<ExtendClass> ExtendClass { get; set; }        public virtual DbSet<BaseClass> BaseClass { get; set; }        public virtual DbSet<ExtendClass2> ExtendClass2 { get; set; }        public virtual DbSet<ExtendClass3> ExtendClass3 { get; set; }}
Step 3 start to try-> Create a database

Add the following code to the Main function and execute it.

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<CodeFirstModel>());using (var context = new CodeFirstModel()){    context.Database.Initialize(true);}

Then we can see the database in SQL Server Management Studio, and there are two tables

Using (CodeFirstModel db = new CodeFirstModel () {BaseClass bc = new BaseClass {Name = ""}; db. baseClass. add (bc); ExtendClass bc1 = new ExtendClass () {Name = "", DescriptionString = ""}; db. extendClass. add (bc1); ExtendClass2 bc2 = new ExtendClass2 {Name = "Sqlserver", Version = "2014"}; db. extendClass2.Add (bc2); db. saveChanges ();}

 

Let's take a look at the data in the database.

Using (CodeFirstModel db = new CodeFirstModel () {// BaseClass bc = new BaseClass {Name = ""}; // db. baseClass. add (bc); // ExtendClass bc1 = new ExtendClass () {Name = "", DescriptionString = ""}; // db. extendClass. add (bc1); // ExtendClass2 bc2 = new ExtendClass2 {Name = "Sqlserver", Version = "2014"}; // db. extendClass2.Add (bc2); ExtendClass3 bc3 = new ExtendClass3 {Name = "C3", Version = "9981", IntNum = 3000, LongNum = 0 xFFFFFFFFFFL}; db. baseClass. add (bc3); db. saveChanges ();}

 

View the database after execution

Using (CodeFirstModel db = new CodeFirstModel () {// BaseClass bc = new BaseClass {Name = ""}; // db. baseClass. add (bc); // ExtendClass bc1 = new ExtendClass () {Name = "", DescriptionString = ""}; // db. extendClass. add (bc1); // ExtendClass2 bc2 = new ExtendClass2 {Name = "Sqlserver", Version = "2014"}; // db. extendClass2.Add (bc2); // ExtendClass3 bc3 = new ExtendClass3 {Name = "C3", Version = "998 1 ", IntNum = 3000, LongNum = 0 xFFFFFFFFFFL}; // db. baseClass. add (bc3); // db. saveChanges (); foreach (var item in db. baseClass) {var cbc3 = item as ExtendClass3; if (cbc3! = Null) {Console. Write (cbc3.ID); Console. Write (": \ t"); Console. WriteLine (cbc3.Name );}}}

We can see the execution result

As you can see, what you read from the base class object set is actually a subclass object. It can be transformed down to the corresponding subclass. Of course, the upward transformation will not be mentioned.

 

Summary

 

The codefirst mode of Entity Framework allows us to use entities in the database as local entities. undoubtedly, this gives our code more flexibility. but at the same time, it makes the database look unfriendly, because it contains more entity ing fields.

 

The ORM framework shields database differences to some extent, but it also shields some database advantages. codefirst makes some complicated data splitting and accelerated processing using stored procedures less friendly. let's quote an old saying that we should not do IT for IT. When our ORM cannot quickly achieve our intended purpose, we may remove the ORM, use the original driver with handwritten SQL and stored procedures for application.


It is said that code first cannot have a generic type. check whether this is required:

Unfortunately, Entity Framework does not support generics at this stage, even if you use OnModelCreating to write custom meta.

I personally think that the database structure is fixed, so the codefirst model is mostly fixed, so there is no need to omit this business-level code and write more attributes, no more lines of code.

If you only want to add, delete, modify, and query data, consider writing a data access layer that supports generics, or use some lightweight orm libraries to support database and type access on the plane.

How to Use CodeFirst for data migration

If you are still
The model that supports the xxx context has been changed after the database is created. Please consider using Code First to migrate and update the database
Find the class library where your database context is located (generally written in the model of the project, and some independent model class libraries)
Open the Nuget package Management Console
Enter: Enable-Migrations, and press Enter.
If correct, Code First migration is enabled for project xxx.
Here are several possible errors:
1. No context type was found in the assembly xxx
The database context is not found in the current project, that is, the "database. cs" inherited by DbContext"
2. The EntityFramework package is not installed on project xxx
The data context has been found in the current project, but there is no EntityFrameWork. You need to install and enter install-package entityframework (I do not know if it is too big)
If the installation is successful, the Migrations folder appears in the project, which records the changes in each data migration.
It is very easy to use, and there is no need to delete the database to regenerate data loss and other issues.
Common statement: enable-Migrations-Force replace migration data file update-database update add-migration add new update File

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.