WEBAPI Frame Construction-data access EF Code First

Source: Internet
Author: User

Why use EF?

I believe a lot of Bo friends and I have this "choice of difficult disease", I have, and now have, this is a common problem of technical people-always want to use a "more perfect" way to achieve, leading to hesitate in technology choice, or always overthrow the technical line of others, and even repeatedly overturned their former ideas, This kind of research spirit is good, but with the increase in age, will find that this habit has become very tired, in fact, it is not necessary. I feel that technically there will never be a "perfect" solution, if the shortcomings to compare and choose, no matter what the final choice, will regret later. Because you always see the flaws in it. ORM Framework also has a lot of, everyone said EntityFramework performance is a bit poor, it generated SQL statement simply can't see, I also thought about dapper, but it to write some SQL statements, this is not what I want to do (purely personal code style preferences). Share why EF is chosen. The requirements of my ORM Framework are this: 1, simple and quick to get started (because I do not want to spend too much energy on this, and EF methods of data is very full); 2, performance as long as the line (not to develop the performance requirements of the product, I think Microsoft's products are not low performance); 3. Later if you want to change the database, it is best not to change the code (this is the main reason I like EF, as long as the data connected to Exchange, DLL replacement, the database can be arbitrarily switched from mysql,sqlserver,oracle)

Why use code First?

1. Simple code

The code for the DB First,code first is more concise, and basically all of the code is really needed. DB First has a lot of auto-generated auxiliary code.

2, writing simple

DB First is also simple under SQL Server, but if it's MySQL or Oracle, there are a lot of problems with the VS configuration, and I've often encountered a "vs" MySQL failure when I was a beginner, or a failure to always generate code after a successful connection. And with code first, you just write the entity codes, although "write more code", but in fact faster than the DB first.

Resources

Recommendation: Http://www.entityframeworktutorial.net/code-first/entity-framework-code-first.aspx

Microsoft Official: https://msdn.microsoft.com/en-us/library/aa937723 (v=vs.113). aspx

Here's how it's practical

Usage and steps

Referencing related packages

If it's a SQL Server database, just reference entityframework.

If it is a MySQL database, refer to the Mysql.data.entity package (dependent Mysql.data package)

Note: In the actual development of some versions of the Mysql.data.entity package is found to have a bug, such as version 6.10.5, it is recommended to install 6.9.10 (Test no problem)

If it is an Oracle database, refer to the Oracle.managedDataAccess.EntityFramework package (dependent oracle.manageddataaccess package)

    Oracle Note: Microsoft has also been out of Oracle's connectivity library, but does not support EF, and now advocates Oracle-odp.net technology. and Odp.net previous version is based on Oracle.dataaccess.dll, this has x86 and x64 bit of points, development is very inconvenient, recommended Oracle.managedDataAccess.dll.

After the package is referenced, the following configuration information is automatically generated in Web. config:

1) under configuration--"configsections node, generate section named EntityFramework

<section name= "EntityFramework" type= "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=6.0.0.0, Culture=neutral, publickeytoken=b77a5c561934e089 "requirePermission=" false "/>

2)

Writing entity classes

The following code

Using system;using system.componentmodel.dataannotations;using System.ComponentModel.DataAnnotations.Schema; Namespace Webapi. entities{    [Table ("Test")] public    class testtable    {        [Key,column (TypeName = "varchar"), MaxLength (50) ] public        string Id {set; get;}        [Column (TypeName = "int")]        public int? Age {set; get;}        [Column (TypeName = "datetime")]        Public DateTime? createdatetime {get; set;}}}    

Entities are described by DataAnnotations in the database type, length, primary key, etc. There is no need to rote their writing, not when reference http://www.entityframeworktutorial.net/code-first/ Stringlength-dataannotations-attribute-in-code-first.aspx on the line.

Writing a database context

1) Create a class that inherits from DbContext

Using System.data.entity;namespace Webapi. entities{public    class Db:dbcontext {//<summary>//        name=dbconnection, DbConnection is the name of the database connection, that is, the Web. config profile node connectionstrings,name the database connection string with a value of dbconnection//        </summary> Public        DB ()            : Base ("Name=dbconnection")        {        }        #region Configure all database tables public        dbset<testtable > testtables {set; get;}        #endregion    }}

2) Configure the database connection string in Web. config

Because the database connection string is important, for convenience, in the actual development is often configured separately in a file, and then in the Web. config to refer to the configuration file.

Create a Connectionstrings.config file that reads as follows

<?xml version= "1.0" encoding= "Utf-8"?><connectionstrings>  <!--SQL Server connection string--  <!- -<add name= "DBConnection" providername= "System.Data.SqlClient" connectionstring= "Data Source = localhost; Initial Catalog = webapiframework; User Id = sa; Password = 1 "  />-->  <!--mysql connection string--  <add name=" DBConnection "Providername=" MySql.Data.MySqlClient "connectionstring=" Data source=localhost;initial Catalog=webapi; User Id=root; password=root;charset=utf8;port=3306; "/>  <!--Oracle Connection string-  <!--<add name=" DBConnection " Providername= "Oracle.ManagedDataAccess.Client" connectionstring= "Data source=localhost; User Id=system; Password=root; "/>--></connectionstrings>

The above will be used to connect the database of common examples, in the future to change the database, just click the database connection string on the line.

Writing test interfaces

The basic approach to code first is three steps above. Let's test it for normal.

1) Create a test interface with the following code:

Using System.linq;using system.web.http;using Webapi. Entities;namespace webapi.example{public    class Eftestcontroller:apicontroller    {        public Ihttpactionresult Get ()        {            using (DB db=new db ())            {                var list = db. Testtables;                return Ok (list. ToList ());}}}    

2) Running the interface

Use postman to access the interface address (GET method): Http://localhost:101/api/EFTest, return the result is an empty JSON array: [];

Note: MySQL is already installed on my computer, but there is no WEBAPI database Ah, why does the interface run properly? The reason is that EntityFramework automatically detects if a database exists, and if it does not, it will create it. The following is a database that EF automatically creates

WEBAPI Frame Construction-data access EF Code First

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.