.NET Core on Mac

From Logic Wiki
Jump to: navigation, search


Installing a package by using .NET CLI

dotnet add package <PackageName>
dotnet restore

The packages you need to install

  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.SqlServer

Installing Entity Framework Commands

To create migrations and update database yoou need to install EF commands

Edit .csproj fie and add the lines below

For VS

<ItemGroup>
  <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools" version="1.1.0"/>
</ItemGroup>

For VS Code

<ItemGroup>
  <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" version="1.0.0"/>
</ItemGroup>

Creating DBContext

public MyDbContext(DbContextOptions<MyDbContext> options) 
   :base(options)

and in startup class

services.AddDbContext<MyDbContext>(options => options.UseSqlServer("......"));

To use UseSqlServer() import namespace

using Microsoft.EntityFrameworkCore;

Store the connection string in appsettings.json

"ConnectionStrings":{"Default":"server=localhost; database=somedb; userid=...;password=....;}

in windows we can add integration security=SSPI instead of username and password

Now in ConfigureServices when calling the UseSqlServer() method you can read connection string like

Configuration.GetconnectionString("Default")

Creating Migrations using CLI

dotnet ef migrations add <MigrationName>
dotnet ef database update

AutoMapper

install these packages

  • AutoMapper
  • AutoMapper.Extensions.Microsoft.DependencyInjection

Register AutoMapper for dependencty injection in Startup.ConfigureServices

services.AddAutoMapper();

Create a profile class to define mappings

public class MappingProfile:Profile{}

in the constructor of this class define maps using CreateMap() Finally to use AutoMapper, inject the IMapper interface to your controller