Entity Framework-postgresql Codefirst

Source: Internet
Author: User
Tags connectionstrings

After several years of renewal and industry recognition of the entity Framework. There are more and more databases that EF can support now. The PostgreSQL database can now use code first to create the database.

Not much to say, the following directly on the process.

First, install the necessary libraries

Execute directly in the VS Package management Console

Install-package Npgsql.entityframework

or right-click into NuGet's management tool to search for npgsql.entityframework.

Dependencies are automatically resolved during installation, and EF 6.0 and Npgsql drivers are installed


Code-first's model is, of course, writing code directly.

//entity class Public classkeyvaluetbl {[Key] [databasegenerated (databasegeneratedoption.identity)] Public LongId {Get;Set; } [Required] Public stringValue {Get;Set; } }//Database Context Public classDb:dbcontext { PublicDB ():Base("name = Db") { }        protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {//the default schema for EF is dbo, but the PG default is public, here you changeModelbuilder.hasdefaultschema (" Public"); }         Public VirtualDbset<keyvaluetbl> KEYVALUETBL {Get;Set; } }


Under normal circumstances, when you install EF, the program configuration document is automatically added. However, the entire document is still posted here.

<?XML version= "1.0" encoding= "Utf-8"?><Configuration>  <configsections>    < Sectionname= "EntityFramework"type= "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=, culture= Neutral, publickeytoken=b77a5c561934e089 "requirepermission= "false" />  </configsections>  <Startup>    <supportedruntimeversion= "v4.0"SKU=". netframework,version=v4.5 " />  </Startup>  <EntityFramework>    <defaultconnectionfactorytype= "System.Data.Entity.Infrastructure.LocalDbConnectionFactory, entityframework">      <Parameters>        <parametervalue= "v12.0" />      </Parameters>    </defaultconnectionfactory>    <providers>      <providerInvariantName= "System.Data.SqlClient"type= "System.Data.Entity.SqlServer.SqlProviderServices, entityframework.sqlserver" />      <providerInvariantName= "Npgsql"type= "npgsql.npgsqlservices, npgsql.entityframework" />    </providers>  </EntityFramework>  <System.Data>    <dbproviderfactories>     <!--note here, when the package is installed, the configuration here is not automatically added -      <Removeinvariant= "Npgsql" />      <Addname= "Npgsql"invariant= "Npgsql"Description= ". Net Framework Data Provider for Postgresql"type= "Npgsql.npgsqlfactory, npgsql" />    </dbproviderfactories>  </System.Data>  <connectionStrings>    <!--connection string corresponding to the database context, host, user, password with your own -    <Addname= "Db"connectionString= "Server=localhost; User Id=postgres; Password = Postgres; Database=efdb "ProviderName= "Npgsql"/>  </connectionStrings></Configuration>

Implementing database initialization with code
classProgram {Static voidMain (string[] args) {            //Initialize the other two in the way you want.//dropcreatedatabaseifmodelchanges//createdatabaseifnotexists            varInitializes =NewDropcreatedatabasealways<model.db>(); using(Model.db DB =Newmodel.db ())            {initializes.initializedatabase (db); }            using(Model.db DB =Newmodel.db ()) {db. Keyvaluetbl.add (Newmodel.keyvaluetbl {Value ="Hello world!" }); Db.                SaveChanges (); Console.WriteLine (db. Keyvaluetbl.first ().            Value); } console.readkey (true); }    }

No accident, you should be able to see the data, and you can open the database with other tools, you will find that the table has been automatically created and there is a piece of data.

Of course, the current driver also supports the migration tool that comes with the entity Framework. Using migration, you can create an index of multiple column combinations, which is very useful. Because there is no big difference with SQL Server operations, this is not the case.

Entity Framework-postgresql Codefirst

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.