13 Aralık 2017

Dotnet Core ile Postgresql

Dotnet Core 2 SDK ve Visual Studio Code kurulu olduğu varsayılmıştır.

elephantsql.com üzerinden denemek için ücretsiz bir postgresql database alabilirsiniz.

Konsol açalım

1) Yeni bir dotnet projesi oluşturalım
mkdir projem 

cd projem

dotnet new webapi


2) Kullanacağımız paketleri kuralım

dotnet add package Microsoft.EntityFrameworkCore.Design

dotnet add package Microsoft.EntityFrameworkCore.Tools

dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL

3)Visual Studio Code ile projeyi açalım. 

code .

4) projem.csproj içerisinde Microsoft.EntityFrameworkCore.Tools.DotNet toolunu ekleyelim.

<dotnetclitoolreference include="Microsoft.EntityFrameworkCore.Tools.DotNet" version="2.0.1">

projem.csproj son hali aşağıdaki gibidir.


<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.0.0" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.1" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" />
  </ItemGroup>

</Project>


5) appsettings.Development.json içerisine TestConnection isminde bir bağlantı cümlesi ekleyelim

"ConnectionStrings":{

    "TestConnection":"Server=XXX;Port=5432;Database=XXX;User Id=XXX;Password=XXX;"

  },

Son hali aşağıdaki gibidir.

{
  "ConnectionStrings":{
    "TestConnection":"Server=XXX;Port=5432;Database=XXX;User Id=XXX;Password=XXX;"

  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

6) Models adında bir klasör oluşturalım ve içerisine

User.cs sınıfını ekleyelim

namespace projem.Models
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
}


ve TestContext.cs ekleyelim

using Microsoft.EntityFrameworkCore;

namespace projem.Models
{
    public class TestContext : DbContext
    {
        public TestContext(DbContextOptions<TestContext> options) : base(options) { }
        public DbSet<User> Users { get; set; }
    }
}

7. Sonuncu ve en önemli adım Startup.cs içerisinde ConfigureService metodunun içerisine EntityFrameworkNpgsql() servisini ekleyelim

 
 services.AddEntityFrameworkNpgsql().AddDbContext<testcontext>(opt =>
                opt.UseNpgsql(Configuration.GetConnectionString("TestConnection"))
            );

Startup.cs en son hali aşağıdaki gibidir.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using projem.Models;


namespace projem
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
             services.AddEntityFrameworkNpgsql().AddDbContext<testcontext>(opt =>
                opt.UseNpgsql(Configuration.GetConnectionString("TestConnection"))
            );
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}


8. Projeyi Kaydet Komut satırına
dotnet ef migrations add InitialCreate
ile ilk migration oluşturdurk ve
dotnet ef database update
ile tarafımızda olan değişiklikeri database üzerinde yansıttık. https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet