0

After executing the migration command Update-DataBase -v.

I get an error.

An attempt to attach an auto-named database for file Bookinist.mdf failed.
A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.


Question: How to fix the error and create a database using migration?

My expectations:

  • create a layer "WPF Core3.1 application";
  • create a layer for working with a database that will work with EFCore;
  • Migrations should create a database in the layer where the application is located (Migration EF Wpf Core 31.v6).

Links

Project: MigrationEFWpfCore31.v6--github.com


Description

I did.
I have created a solution
enter image description here

appsettings.json

{
  "ConnectionStrings": {
    "DataBase": "Data Source=(localdb)\\MSSQLLocalDB;AttachDbFileName=Bookinist.mdf;Integrated Security=True"
  }
}

App.xaml.cs

public partial class App : Application
{       
        public static IHostBuilder CreateHostBuilder(string[] args) => Microsoft.Extensions.Hosting.Host
                .CreateDefaultBuilder(args)
                .ConfigureServices(
                    (hostContext, services) => services
                       .AddDbContext<ContextDBBookinist>(opt =>
                       {                           
                           opt.UseSqlServer(hostContext.Configuration.GetConnectionString("Database"));
                       } 
                    )
        );
}

I opened the Package Manager Console.
I have installed The default project is - MigrationEFWpfCore31.v6.DAL.
Ran the Add-Migration Initial -v command.
enter image description here

enter image description here

enter image description here

I ran the Update-DataBase -v command. enter image description here

enter image description here

An attempt to attach an auto-named database for file Bookinist.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

Solution-1. (Not working)

Project Solution-1. MigrationEFWpfCore31.v6--Test1--github.com

Added the App_Data folder
enter image description here

Added [DataDirectory]\\App_Data\\

Full code:

{
  "ConnectionStrings": {
    "DataBase": "Data Source=(localdb)\\MSSQLLocalDB;AttachDbFileName=[DataDirectory]\\App_Data\\Bookinist.mdf;Integrated Security=True"
  }
}

App.xaml.cs
Added

string path = Directory.GetCurrentDirectory();
//  ...
Configuration.GetConnectionString("DefaultConnection")
.Replace("[DataDirectory]", path)));

Full code:

public partial class App : Application
{   
    public static IHostBuilder CreateHostBuilder(string[] args) => Microsoft.Extensions.Hosting.Host
            .CreateDefaultBuilder(args)
            .ConfigureServices(
                (hostContext, services) => services
                    .AddDbContext<ContextDBBookinist>(opt =>
                    {
                        string path = Directory.GetCurrentDirectory();
                        opt.UseSqlServer(hostContext.Configuration.GetConnectionString("Database")
                            .Replace("[DataDirectory]", path));
                    } 
                )
    );
}

Package Manager Console
I entered the command Add-Migration Initial -v enter image description here

enter image description here

I entered the command Update-DataBase -v enter image description here

enter image description here

Error text:

An attempt to attach an auto-named database for file e:\Projects\Projects\5058\01_pr\01\MigrationEFWpfCore31.v6\MigrationEFWpfCore31.v6\App_Data\Bookinist.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

Solution-2 (Did not check)

Maybe the migration works with a different version of MSSQLLocalDB, and in Microsoft SQL Server Management Studio am I seeing MSSQLLocalDB of a different version?


Note

Microsoft SQL Server Management Studio.
enter image description here

MigrationEFWpfCore31.v6

MigrationEFWpfCore31.v6.csproj

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

    <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <UseWPF>true</UseWPF>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0-rc.2.20475.6" />

        <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
        <PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0-rc.2.20475.5" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.0" />
    </ItemGroup>

    <ItemGroup>
        <ProjectReference Include="..\MigrationEFWpfCore31.v6.DAL\MigrationEFWpfCore31.v6.DAL.csproj" />
    </ItemGroup>
    <ItemGroup>
        <None Update="appsettings.json">
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
    </ItemGroup>
    <ItemGroup>
      <Folder Include="App_Data\" />
    </ItemGroup>

</Project>

MigrationEFWpfCore31.v6.DAL

MigrationEFWpfCore31.v6.DAL.csproj

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

    <PropertyGroup>
        <TargetFramework>netstandard2.1</TargetFramework>
        <Nullable>enable</Nullable>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0-rc.2.20475.6" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0-rc.2.20475.6" />
    </ItemGroup>

</Project>

Author.cs

using System.Collections.Generic;


namespace MigrationEFWpfCore31.v6.DAL.Entities
{
    public class Author 
    {
        public int AuthorId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public List<Book> Books { get; set; }
    }
}

Book.cs

namespace MigrationEFWpfCore31.v6.DAL.Entities
{
    public class Book 
    {    
        public int BookId { get; set; }
        public string Title { get; set; }
        public Author Author { get; set; }
    }
}

ContextDBBookinist.cs

using Microsoft.EntityFrameworkCore;


namespace MigrationEFWpfCore31.v6.DAL.Entities
{
    public class ContextDBBookinist : DbContext
    {

        public DbSet<Author> Authors { get; set; }
        public DbSet<Book> Books { get; set; }

        public ContextDBBookinist(DbContextOptions<ContextDBBookinist> options) : base(options)
        {
            
        }
    }
}
eusataf
  • 807
  • 1
  • 12
  • 24
  • Migration has two modes 1) Create 2) Update. Migration should only be used when the structure of the database tables/properties are changed and not run every time you change the data in the database. Migration takes the c# dbContext classes and creates a mapping to the database tables/fields. The error implies you are doing a CREATE and not an UPDATE. Or the database name already exists in the Server and you are using CREATE. Or you are running Migration when you do not need to run Migration. – jdweng Apr 15 '23 at 14:51
  • @jdweng I'm sorry I don't understand you well... My head doesn't work.. I expect: **1.** The developer has entered commands **2.** As a result of the migration, a database was created in the project. **Question-1:** Is that impossible? Your decision: **1.** The developer must add an empty database (Bookinist.mdf file) to the project. **2.** Enter the command `Update-DataBase -v` **3.** Result: tables with fields will be created in Bookinist.mdf. The tables will be empty (without data). **Question-2:** Did I understand you correctly? – eusataf Apr 15 '23 at 15:02
  • MDF is the file in SQL Server that contains the database. A server can have more than one database Answers 1 ) Yes, Migration takes the c# classes and creates a mapping to the database and creates tables. 2) Update-Database : As I said Migration has to modes Create and Update. Create make a new mdf file while update doesn't. Update changes an existing datgabase. 3) The tables will contain fields (properties/columns) but no data. – jdweng Apr 15 '23 at 16:56

0 Answers0