Publishing C# project application with SQL Server local database

6ojccjat  于 2023-03-28  发布在  C#
关注(0)|答案(1)|浏览(156)

I have created a win C# application with database included using .NET Framework Data Provider for SQL Server everything works great and for the database path I'm using this path

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\tommy\Documents\dbIMS.mdf;Integrated Security=True;Connect Timeout=30");

The application after publishing works great on my PC put when I open it in my other PC it doesn't work. I have tried to changed the path of the database with same application folder also didn't work and I have installed the SQL Server express on my other PC also . I'm getting this error when I try to connect to my application via SQL

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connection.(Provider: SQL Network Interfaces, Error:52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)

How can I publish the project with the database so it can work on any PC?

ff29svar

ff29svar1#

Include the require files to the project and then for each file needed, right click on properties, Copy to Output directory: always

Also if you are working on Visual Studio 2019 or above, open the csproj file of your project with a notepad and check for this:

<ItemGroup>
    <Content Include="your_file">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

and/or

<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
  <ItemGroup>
    <DataModelFiles Include="$(ProjectDir)..\yourproject\yourfile" />
  </ItemGroup>
  <Copy SourceFiles="@(DataModelFiles)" DestinationFolder="$(PublishDir)" SkipUnchangedFiles="false" />
</Target>

相关问题