Entity freamwork codefirst Connect PostgreSQL database

Source: Internet
Author: User
Tags postgresql connectionstrings

EF's code first is a powerful and useful feature that allows you to write code and finally build a database based on your code, very well in line with the requirements of OO design, regardless of the database level (of course not completely regardless of), just object design.

First of all, tell me about my test environment: EF 6.0/postgresql 9.2

Premise: The computer has the PostgreSQL database installed and the ODBC data source configured to ensure that the computer supports PostgreSQL.

The first step: Add a program to the EF reference, there is a lazy way is to add an empty code Fist ADO. NET Entity Data model, so that VS will automatically help you add references to EF and related DLLs

Step Two: Add a reference to Npgsql for Entity freamwork with NuGet, NuGet will automatically help you add Npgsql and npgsql.entityfreamwork references, and will add a configuration to your config file.

Step three: Configure config file

1<?xml version="1.0"encoding="Utf-8"?>2<configuration>3<configSections>4<section name="EntityFramework"Type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=6.0.0.0, culture= Neutral, publickeytoken=b77a5c561934e089"requirepermission="false"/>5</configSections>6<startup>7<supportedruntime version="v4.0"sku=". netframework,version=v4.5"/>8</startup>9<entityFramework>Ten<defaultconnectionfactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> One<parameters> A<parameter value="v11.0"/> -</parameters> -</defaultConnectionFactory> the<providers> -<provider invariantname="Npgsql"Type="npgsql.npgsqlservices, Npgsql.entityframework"/> -</providers> -</entityFramework> +<system.data> -<DbProviderFactories> +<remove invariant="Npgsql"/> A<add name="npgsql Data Provider"Invariant="Npgsql"description=". Net Data Provider for PostgreSQL"Type="npgsql.npgsqlfactory, Npgsql, version=2.2.3.0, culture=neutral, Publickeytoken=5d8b90d52f46fda7"support="FF"/> at</DbProviderFactories> -</system.data> -<connectionStrings> -<add name="ConnectionStr"connectionstring="server=127.0.0.1;port=5432;database=test;uid=*****;p wd=*****"Providername="Npgsql"/> -</connectionStrings> -</configuration>
Config

In this process, I have a relatively clear understanding of several places:

1.<add name= "ConnectionStr" connectionstring= "server=127.0.0.1;port=5432;database=test;uid=postgres;pwd= baixu963. "Providername=" Npgsql "/> In this sentence, ProviderName to fill in is to access the database of the ADO namespace, such as SQL Server is system.data.sqlclient,mysql should be: mysql.data.mysqlclient,.net access PostgreSQL is The driver provided by the Open source project Npgsql, the namespace is also Npgsql, so here's Providername= "Npgsql".

2. In Webconfig, the configsections node must be in the first, do not change his position.

3.DbProviderFactories node: Chinese meaning: Database vendor Factory, This is also a configuration for. NET access to the database, because this is Microsoft, and his support for SQL Server has already given the default value, so we usually do not need to configure SQL Server, but the configuration of some other databases, it needs to be modified. Among them, the most important is invariant this thing, this corresponds to the database of the ADO-driven namespace. There is also a type to be aware of, and the following is the syntax for MySQL:

1<DbProviderFactories>2<add name="MySQL Data Provider"3Invariant="MySql.Data.MySqlClient"4description=". Net Framework Data Provider for MySQL"5Type="MySql.Data.MySqlClient.MySqlClientFactory, Mysql.data, version=5.2.5.0, Culture=neutral, publickeytoken= C5687FC88969C44D"/>6</DbProviderFactories>
MYSQL dbproviderfactories

The configuration file is here, so let's start with the code section below.

First, give a person class:

1   Public class Person2     {3 [Key]4          Public intId {Get;Set; }5[Stringlength ( +)]6          Public stringName {Get;Set; }7}
Person

ID above the attribute tag key means that this is a primary key, name above the stringlength is to tell the database, this field is 32 length.

Then, create a new DbContext (if you have just created an empty code Fist ADO. NET Entity Data Model refers to the EF, he will automatically help you build a demo out, you can directly change that), not much explanation, directly on the code,

public class Efdbcontext:dbcontext
{
Public Efdbcontext ()
: Base ("Name=connectionstr")
{

}
Public virtual dbset<person> person {get; set;}
}

Where name corresponds to the name of the connection string in the database, and the following dbset<t> corresponds to a table in the database, note that this dbset must virtual,ef need to rewrite it.

Basic we have finished writing, let's try it, I am a console program, so directly the code of the console, you are free.

1 class Program2     {3         Static voidMain (string[] args)4         {5Efdbcontext context=NewEfdbcontext ();6Person person=NewPerson ();7Person. Name ="Baiyunchen";8 context. Person.add (person);9 context. SaveChanges ();Ten             varp = Context. Person.firstordefault (x = X.name = ="Baiyunchen") ??NewPerson (); One Console.WriteLine (p.name); A Console.readkey (); -         } -}
Test Code

Waiting for him to output the name of P, and then go to the database, he has helped to automatically build the library, build tables, insert data, everything OK.

Strangely, he created a new people table, after which I forced the person class to add the [table= "person"] so that I built the man table, do not know which keyword conflicts with.

In addition, I found that after the change in your entity, EF will become an abnormal problem if you need to deal with it. First, I have to go back to studying EF.

Entity freamwork codefirst Connect PostgreSQL database

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.