---
# System prepended metadata

title: Console で Entity Framework Core を使用する LocalDB 2023-07-03
tags: [LocalDB, EF Core, Entity Framework Core]

---

---
lang: ja-jp
breaks: true
---

## appsettings.json

```json=
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=XXXX_DATABASE;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}
```
![](https://hackmd.io/_uploads/r1Nr-ZgKh.png)

## csproj

```xml=
・・・
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.8" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.8">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.8" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.4" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
  </ItemGroup>
・・・
```

## BlogDbContext.cs

```csharp=
public class Blog
{
    public int Id { get; set; }
    public string? Name { get; set; }

    public override string ToString()
    {
        return $"[{Id}][{Name}]";
    }
}


public class BlogDbContext : 
    DbContext
{
    public DbSet<Blog> Blogs { get; set; } = null!;

    public string? _connectionStrings { get; } = null;

    public BlogDbContext(
        )
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        string? connectionString = configuration.GetConnectionString("DefaultConnection");
        if (connectionString is null)
        {
            Console.WriteLine("No connection string found.");
            return;
        }

        _connectionStrings = connectionString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer(_connectionStrings);
}
```

## Program.cs

```csharp=
BlogDbContext blogDbContext = new();

blogDbContext.Add(new Blog
{
    Name = "My Blog"
});
blogDbContext.SaveChanges();

Blog? blog =blogDbContext.Blogs
    .OrderBy(b => b.Name)
    .FirstOrDefault();

Console.WriteLine(blog);

if (blog != null)
{
    blogDbContext.Remove(blog);
    blogDbContext.SaveChanges();
}

Console.WriteLine("completed.");
```

## マイグレーション

```shell=
dotnet ef migrations add InitialCreate
```

```shell=
dotnet ef database update
```

```shell=
dotnet ef database drop
```

