<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>sql tutorial &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/sql-tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Thu, 16 Feb 2023 07:10:27 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>sql tutorial &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Reduce Connection Pools Hitting Multiple Databases</title>
		<link>https://topreviewhostingasp.net/how-to-reduce-connection-pools-hitting-multiple-databases/</link>
					<comments>https://topreviewhostingasp.net/how-to-reduce-connection-pools-hitting-multiple-databases/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 16 Feb 2023 07:09:12 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[database issue]]></category>
		<category><![CDATA[fix connection pool issue]]></category>
		<category><![CDATA[sql database]]></category>
		<category><![CDATA[sql database hang]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sql tips]]></category>
		<category><![CDATA[sql tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3434</guid>

					<description><![CDATA[Microsoft’s connection pooling built in to the .Net Framework greatly improves performance by allowing hundreds of database calls to share the same pool of connections used to connect to the database. The .Net Framework creates a new pool of connections for each unique connection string. This works fantastic when your web application connects to a [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Microsoft’s connection pooling built in to the .Net Framework greatly improves performance by allowing hundreds of database calls to share the same pool of connections used to connect to the database. The .Net Framework creates a new pool of connections for each unique connection string. This works fantastic when your web application connects to a single database and all your connections use the same connection string. It even works well if you have two or three different connection strings, but for each unique connection string value, the .Net Framework creates a new connection pool. If your web site has dozens of different databases to connect to, you may find your application creates dozens of connection pools which begins to consume a lot of resources on both the web server and SQL Server.</p>



<p>There is a fairly easy way to eliminate this problem, and that is to use the ChangeDatabase method on the Connection object.</p>



<p>Our web application was connecting to one of fifty different databases that all reside on the same instance of SQL Server. Each of our clients has their own database. But our application was creating fifty different connection pools. We were able to have all the clients share a single pool of connections by first connecting to a neutral database, then redirecting the connection to the desired database.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.asphostportal.com" target="_blank" rel="noreferrer noopener"><img fetchpriority="high" decoding="async" width="300" height="271" class="wp-image-2584 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure></div>


<p>We created a new database on the server, called Central, then we had all the connections to the database first connect to Central as the Initial Catalog. The next step was to call ChangeDatabase to switch to the desired database. This technique did not create a new connection to SQL Server and did not create a new connection pool on the .Net client. Microsoft documentation mentions this technique here: <a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling#pool-fragmentation-due-to-many-databases" target="_blank" rel="noreferrer noopener">https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling#pool-fragmentation-due-to-many-databases</a> , but their example code does not show the ChangeDatabase method, which is more efficient than their example.</p>



<p>In a nutshell, you can do this:</p>



<pre class="wp-block-code"><code>connection.Open();
connection.ChangeDatabase(“Client1”);</code></pre>



<p>I created a simple Windows Form App to test the idea.  The test app runs a query to return the name of the current database it is in.  Also, on the SQL Server I run a query to see all the connections that exist.  Doing this I was able to prove that using ChangeDatabase did not create a new connection to SQL Server and my .Net SQL Connection Object was pointing at the correct desired database.  Sample code, query, and output is below:</p>



<p>Sample C# .Net Forms App:</p>



<pre class="wp-block-code"><code>using System;
using System.Data.SqlClient;
using System.Windows.Forms;
 
namespace SQLConnectionTest
{
    public partial class Form1 : Form
    {
        //https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling#pool-fragmentation-due-to-many-databases
        private void button1_Click(object sender, EventArgs e)
        {
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=model;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=msdb;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            { 
                connection.Open();
                connection.ChangeDatabase("TempDb");
                RunSQL(connection, "select DB_NAME()");
            }
 
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                connection.ChangeDatabase("TempDb");
                RunSQL(connection, "select DB_NAME()");
                connection.ChangeDatabase("model");
                RunSQL(connection, "select DB_NAME()");
            }
        }
 
        public static void RunSQL(SqlConnection connection, string queryString)
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            try
            {
                SqlDataReader reader = command.ExecuteReader(); 
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        Console.WriteLine("\t{0}", reader[0]);
                    }
                    reader.Close();
                }
            }
            catch (Exception ex){Console.WriteLine(ex.Message);}
        }
        public Form1()
        {
            InitializeComponent();
        }
 
 
    }
}</code></pre>



<p>Output from Running the App written to console:</p>



<pre class="wp-block-code"><code>master
model
msdb
master
tempdb
master
tempdb
model</code></pre>



<p>Query to see connections on SQL Server:</p>



<pre class="wp-block-code"><code>CREATE TABLE #TmpLog
(SPID int, Status VARCHAR(150), Login varchar(100), HostName VARCHAR(150), BlkBy varchar(30), DBName varchar(60), Command varchar(500),
CPUTime int, DiskIO int, LastBatch varchar(20), ProgramName varchar(200), SPID2 int, requestid int)
INSERT INTO #TmpLog
EXEC sp_who2
SELECT SPID, Status, Login, HostName, BlkBy, DBName, Command, ProgramName
FROM #TmpLog
where STATUS not in (‘BACKGROUND’) and Command not in (‘TASK MANAGER’) and ProgramName like ‘.net%’
DROP TABLE #TmpLog
go</code></pre>



<p>Results of running query on SQL Server:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="143" class="wp-image-3435" src="https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-1024x143.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-1024x143.png 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-300x42.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-768x107.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-1536x214.png 1536w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-50x7.png 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query.png 2013w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-reduce-connection-pools-hitting-multiple-databases/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Use Entity Framework Connect to SQL Server</title>
		<link>https://topreviewhostingasp.net/how-to-use-entity-framework-connect-to-sql-server/</link>
					<comments>https://topreviewhostingasp.net/how-to-use-entity-framework-connect-to-sql-server/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 18 Mar 2022 07:44:06 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[.net core 6]]></category>
		<category><![CDATA[asp net core 6 tips]]></category>
		<category><![CDATA[asp net core 6 tutorial]]></category>
		<category><![CDATA[entity framework tips]]></category>
		<category><![CDATA[entity framework tutorial]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sql tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3013</guid>

					<description><![CDATA[This post shows goes through the steps to connect a .NET 6 API to SQL Server using Entity Framework Core, and automatically create/update the SQL Server database from code using EF Core migrations. We&#8217;ll start with an example .NET 6 CRUD API from a tutorial I posted recently, it uses the EF Core InMemory db [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>This post shows goes through the steps to connect a .NET 6 API to SQL Server using Entity Framework Core, and automatically create/update the SQL Server database from code using EF Core migrations.</p>



<p>We&#8217;ll start with an example .NET 6 CRUD API from a tutorial I posted recently, it uses the EF Core InMemory db provider by default for testing, we&#8217;ll update it to connect to a SQL Server database and run EF Core migrations to auto generate the database and tables from code. </p>



<h2 class="wp-block-heading">Requirements!</h2>



<p>To follow the steps in this tutorial you&#8217;ll need the following:</p>



<ul>
<li><a href="https://dotnet.microsoft.com/download" target="_blank" rel="noreferrer noopener">.NET SDK</a> &#8211; includes the .NET runtime and command line tools.</li>
<li><a href="https://code.visualstudio.com/" target="_blank" rel="noreferrer noopener">Visual Studio Code</a> &#8211; code editor that runs on Windows, Mac and Linux. If you have a different preferred code editor that&#8217;s fine too.</li>
<li><a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp" target="_blank" rel="noreferrer noopener">C# extension</a> for Visual Studio Code &#8211; adds support to VS Code for developing .NET applications.</li>
<li>SQL Server &#8211; you&#8217;ll need access to running SQL Server instance for the API to connect to, it can be remote (e.g. Azure, AWS etc) or on your local machine. The Express edition of SQL Server is available for free at <a href="https://www.microsoft.com/sql-server/sql-server-downloads" target="_blank" rel="noreferrer noopener">https://www.microsoft.com/sql-server/sql-server-downloads</a>.</li>
</ul>



<h2 class="wp-block-heading">Download &amp; Run the example .NET 6 API</h2>



<p>Follow these steps to download and run the .NET 6 CRUD API on your local machine with the default EF Core InMemory database:</p>



<ol>
<li>Download or clone the tutorial project code from <a href="https://github.com/cornflourblue/dotnet-6-crud-api" target="_blank" rel="noreferrer noopener">https://github.com/cornflourblue/dotnet-6-crud-api</a></li>
<li>Start the api by running <code>dotnet run</code> from the command line in the project root folder (where the WebApi.csproj file is located), you should see the message <code>Now listening on: http://localhost:4000</code>.</li>
<li>You can test the API directly with a tool such as <a href="https://www.postman.com/downloads" target="_blank" rel="noreferrer noopener">Postman</a>.</li>
</ol>



<h4 class="wp-block-heading">Starting in debug mode</h4>



<p>You can also start the application in debug mode in VS Code by opening the project root folder in VS Code and pressing F5 or by selecting Debug -&gt; Start Debugging from the top menu, running in debug mode allows you to attach breakpoints to pause execution and step through the application code.</p>



<h2 class="wp-block-heading">Update .NET 6 API to use SQL Server</h2>



<h4 class="wp-block-heading"><br />Add SQL Server database provider from NuGet</h4>



<p>Run the following command from the project root folder to install the EF Core database provider for SQL Server from NuGet:</p>



<pre class="wp-block-code"><code>dotnet add package Microsoft.EntityFrameworkCore.SqlServer</code></pre>



<h4 class="wp-block-heading">Add connection string to app settings</h4>



<p>Open the <code>appsettings.json</code> file and add the entry <code>"ConnectionStrings"</code> with a child entry for the SQL Server connection string (e.g. <code>"WebApiDatabase"</code>), the connection string should be in the format <code>"Data Source=[DB SERVER URL]; Initial Catalog=[DB NAME]; User Id=[USERNAME]; Password=[PASSWORD]"</code>, or to connect with the same account that is running the .NET API use the connection string format <code>"Data Source=[DB SERVER URL]; Initial Catalog=[DB NAME]; Integrated Security=true"</code>.</p>



<p>When EF Core migrations generates the database, the <code>Initial Catalog</code> value will be the name of the database created in SQL Server.</p>



<p>The updated <code>appsettings.json</code> file with the connection string should look something like this:</p>



<pre class="wp-block-code"><code>{
    "ConnectionStrings": {
        "WebApiDatabase": "Data Source=localhost; Initial Catalog=dotnet-6-crud-api; User Id=testUser; Password=testPass123"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    }
}</code></pre>



<h4 class="wp-block-heading">Update Data Context to Use SQL Server</h4>



<p>The <code>DataContext</code> class located at <code>/Helpers/DataContext.cs</code> is used for accessing application data through Entity Framework. It derives from the Entity Framework <code>DbContext</code> class and has a public <code>Users</code> property for accessing and managing user data.</p>



<p>Update the <code>OnConfiguring()</code> method to connect to SQL Server instead of an in memory database by replacing <code>options.UseInMemoryDatabase("TestDb");</code> with <code>options.UseSqlServer(Configuration.GetConnectionString("WebApiDatabase"));</code>.</p>



<p>The updated <code>DataContext</code> class should look like this:</p>



<pre class="wp-block-code"><code>namespace WebApi.Helpers;

using Microsoft.EntityFrameworkCore;
using WebApi.Entities;

public class DataContext : DbContext
{
    protected readonly IConfiguration Configuration;

    public DataContext(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        // connect to sql server with connection string from app settings
        options.UseSqlServer(Configuration.GetConnectionString("WebApiDatabase"));
    }

    public DbSet&lt;User&gt; Users { get; set; }
}</code></pre>



<h2 class="wp-block-heading">Create SQL Database from code with EF Core Migrations</h2>



<h4 class="wp-block-heading"><br />Install dotnet ef tools</h4>



<p>The .NET Entity Framework Core tools (<code>dotnet ef</code>) are used to generate EF Core migrations, to install the EF Core tools globally run <code>dotnet tool install -g dotnet-ef</code>, or to update run <code>dotnet tool update -g dotnet-ef</code>. For more info on EF Core tools see <a href="https://docs.microsoft.com/ef/core/cli/dotnet" target="_blank" rel="noreferrer noopener">https://docs.microsoft.com/ef/core/cli/dotnet</a></p>



<h4 class="wp-block-heading">Add EF Core Design package from NuGet</h4>



<p>Run the following command from the project root folder to install the EF Core design package, it provides cross-platform command line tooling support and is used to generate EF Core migrations:</p>



<pre class="wp-block-code"><code>dotnet add package Microsoft.EntityFrameworkCore.Design</code></pre>



<h4 class="wp-block-heading">Generate EF Core migrations</h4>



<p>Generate new EF Core migration files by running the command <code>dotnet ef migrations add InitialCreate</code> from the project root folder (where the WebApi.csproj file is located), these migrations will create the database and tables for the .NET Core API.</p>



<h4 class="wp-block-heading">Execute EF Core migrations</h4>



<p>Run the command <code>dotnet ef database update</code> from the project root folder to execute the EF Core migrations and create the database and tables in SQL Server.</p>



<p>Check SQL Server and you should now see your database with the tables <code>Users</code> and <code>__EFMigrationsHistory</code>.</p>



<h2 class="wp-block-heading">Restart .NET 6.0 CRUD API</h2>



<p>Stop and restart the API with the command <code>dotnet run</code> from the project root folder, you should see the message <code>Now listening on: http://localhost:4000</code> and the API should now be connected to SQL Server.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-use-entity-framework-connect-to-sql-server/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Few Errors in SQL Server and How to Fix it</title>
		<link>https://topreviewhostingasp.net/few-errors-in-sql-server-and-how-to-fix-it/</link>
					<comments>https://topreviewhostingasp.net/few-errors-in-sql-server-and-how-to-fix-it/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Wed, 27 Jan 2021 03:33:41 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[error sql server]]></category>
		<category><![CDATA[how to fix sql error]]></category>
		<category><![CDATA[sql error]]></category>
		<category><![CDATA[sql hosting]]></category>
		<category><![CDATA[sql tips]]></category>
		<category><![CDATA[sql tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2873</guid>

					<description><![CDATA[When starting to work with Entity Framework and SQL Server, you often run into the same errors. Sometimes these errors are caused by missing permissions for the database connection, and sometimes it&#8217;s caused the way that the database is accessed. In this article, we will go through some of the most common errors and some [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>When starting to work with Entity Framework and SQL Server, you often run into the same errors. Sometimes these errors are caused by missing permissions for the database connection, and sometimes it&#8217;s caused the way that the database is accessed. In this article, we will go through some of the most common errors and some of the possible ways these errors could be fixed.</p>



<p>In Sql Server, <strong>user accounts and credentials</strong> are set at the server level, not at the database level. When you deploy an SQL database, only the database info moves over. You need to connect to the Database Server in your <strong>deployed environment</strong> , set up the username and password you want to use, and give the account appropriate permissions into the database. So, first you have to make sure that the user exist on <strong>SQL Server</strong> , that the user is enabled, and has access (mapped) to the correct database.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="642" height="359" class="wp-image-2874 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/01/sql-error.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/01/sql-error.jpg 642w, https://topreviewhostingasp.net/wp-content/uploads/2021/01/sql-error-300x168.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/01/sql-error-50x28.jpg 50w" sizes="(max-width: 642px) 100vw, 642px" /></figure>
</div>



<h2 class="wp-block-heading">How to Fix Login failed for user &#8216;myUsername&#8217;</h2>



<p>At first glance, this seems like it would cover a quite simple error: That the user credentials passed were not valid. This would seem like it could only be a problem with the connection string like a misspelling of the username or password, and that&#8217;s one of the possible causes of the problem. It could also be a problem in the SQL Server like that your user does not have permission to access the database or that the server does not allow SQL Server authentication. The local version of SQL Server has the Server authentication set to Windows Authentication mode by default, which does not enable the possibility to connect without Integrated Security.</p>



<p>The measures one can take to fix the problem are the following:</p>



<ol>
<li>Check that the User Id and Password in the connection string are correct.</li>
<li>Ensure that <code>Integrated Security</code> is set to <code>False</code> in the connection string.</li>
<li>Check that the user is present in <code>Security&gt;Logins</code> in the SQL Server connection in Microsoft SQL Server Management Studio.</li>
<li>Try resetting the password of the user.</li>
<li>Ensure that SQL Server authentication is enabled for the server in <code>Server Properties&gt;Security&gt;Server authentication</code> and then select <code>SQL Server and Windows Authentication mode</code>.</li>
</ol>



<h2 class="wp-block-heading">How to Fix Cannot open database &#8220;myDB&#8221; requested by the login. The login failed.</h2>



<p>The error states that there could not be an established connection to a specific database on the server. This could mean that the specified database in the connection string does not exist or that there was a typo in the connection string.</p>



<p>Possible solutions to the problem could be:</p>



<ol>
<li>Check that there are no typos in the <code>database</code> field in the connection string.</li>
<li>If your project is code-first, ensure that you&#8217;ve called <code>myContext.Database.EnsureCreated()</code> before using your context.</li>
<li>If your project is database-first, check the server if the database is present on the server using Microsoft SQL Server Management Studio.</li>
</ol>



<h2 class="wp-block-heading">How to Fix A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.</h2>



<p>This error states that it was not possible to connect to the specified server. The error often comes together with a long wait time because it wants to make sure that it does not just have a slow connection. A typo could cause the error in the connection string or that the server is configured wrong.</p>



<p>These are some of the ways to troubleshoot the problem:</p>



<ol>
<li>Check that the <code>server</code> field in the connection string is written correctly.</li>
<li>Ensure that remote connection is allowed in Microsoft SQL Server Management Studio in <code>Server Properties&gt;Connection&gt;Remote server connections</code>.</li>
<li>When installing Microsoft SQL Server Management Studio, you also get a program called <code>SQL Server Configuration Manager</code>. This can only be used on the computer that the server is running. In <code>SQL Network Configuration&gt;Protocols for SERVERNAME</code> <code>TCP/IP</code> needs to be enabled for it to be accessed.</li>
</ol>



<h2 class="wp-block-heading" id="microsoftentityframeworkcoredbupdateexception">Microsoft.EntityFrameworkCore.DbUpdateException</h2>



<p>This error covers a lot of different errors. What they all have in common is that Entity Framework failed to save the changes to the database. It is essential to inspect the inner exceptions. It is often just a wrapper around all the <code>System.Data.SqlClient.SqlException</code>&#8216;s that occur when the connection is established.<br />Since the ways to fix these errors are unique to each case, we will list some common causes and how to avoid and fix these errors in general terms.</p>



<p><strong>There have been changes to the models that Entity Framework uses in your project</strong><br />Entity Framework creates all the tables in a database by itself, but when the models in a project start to change, there is a clash between what Entity Framework expects and what&#8217;s actually on the SQL Server. A way to solve this is by using the <a href="https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations">Migration feature</a> from Entity Framework when you make changes to your models.</p>



<p><strong>The same SQL Server is used for many projects</strong><br />When a lot of projects use the same database by accident or intentionally, there can be clashes in the naming of tables. This would mean that one project&#8217;s Entity Framework connection would think that its table was made, while the scheme is the one of another project. This can be avoided by using unique database names for different projects.</p>



<p><strong>Duplicate of entries with the same primary key</strong><br />If multiple entries with the same primary key are inserted into a table, then there is a conflict in the database. This can sometimes be solved by doing <code>context.SaveChanges()</code> only once per update and sometimes be avoided by explicitly making foreign keys in one-to-many relations instead of letting Entity Framework handle it.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/few-errors-in-sql-server-and-how-to-fix-it/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
