Failed to create database Entity Framework code-first - c#

I'm trying to create a database using Entity Framework with a code-first approach, but it fails on creating the database with this exception:
Unhandled Exception: System.Data.DataException:
An exception occurred while initializing the database. See the InnerException for details.
System.Data.Entity.Core.EntityException: The underlying provider failed on Open.
System.Data.SqlClient.SqlException: Cannot open database "X.Xcontext" requested by the login. The login failed. Login failed for user 'This-PC\ME'.
Any idea how to resolve this ?

Your user does not have permissions to create a database, you will need to contact your DBA for permissions, or depending on where you work you'll need to create a ticket to have someone create the database for you.

Well, Problem solved when I just renamed my DbContext..Don't know why,but it worked for me!

Related

Can't initialize local SQL Server database with EFCore commandline tools

I've been trying to follow several different tutorials with EFCore and .net core and I've been totally blocked at the point where I try and create a local database.
I've used both the powershell tools and the commandline tools to try and create an initial migration (or do anything, really).
I consistently get the error:
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.)
The database does not currently exist on the system, though local SQL Server appears to be up and running.
Here is the c# code for adding the context:
services.AddDbContextPool<TestDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestDb")
)
);
This is the connection string code:
"TestDb": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=TestDb"
I get similar errors whether I run add-migration, dotnet ef migration add, or dotnet ef dbcontext info. (note: with the dotnet calls I am using the -s ..\{webproject}\{webproject}.csproj property
I've also messed with the connection string by adding various combinations of Trusted_Connection=True; MultipleActiveResultSets=True;, and Integrated Security=true.
I've gone into SSMS and ensured the Server authentication is SQL Server and Windows Authentication Mode and that Maximum Connections is set to 0 (unlimited). I've also gone to logins and tried adding the user to pretty much all the server roles.
So, yeah, I'm pretty confused. I've worked with EF for years, though this is my first experience with EFCore and I'm definitely more of a developer than a SQL Admin. This is also my first time trying to use the local db on this particular computer.
Edit: Looking at error.log in AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\mssqllocaldb I see this error:
2020-01-28 10:15:03.50 Logon Error: 18456, Severity: 14, State: 38.
2020-01-28 10:15:03.50 Logon Login failed for user 'LAPTOP-NC6HQ4TB\ripli'. Reason: Failed to open the explicitly specified database 'TestDb'. [CLIENT: <named pipe>]
Which is confusing. Of course I can't open the specified database. The entire point is I want to create a DB that doesn't yet exist.
Found the answer. Sorry to everyone who tried to help, as you wouldn't have had enough information to solve it.
In the DbContext I had tried to add some code to the constructor to try and populate some data to the database as part of a test. This caused several problems. If the Database hadn't yet been created it tried to connect to the DB before it had been created, which caused the problems I described.
Furthermore, if I had created the db manually it would try to access the DbSets (which had not yet been created), and then complain that the set name was invalid (which, at this point it was.
This all might have been fine if the DB had been created in advance, but since I was using the DbContext to construct the database, it understandably caused problems.
And all of this headache would have been avoided had I not violated SRP and not tried to (even temporarily) hijack a context constructor to hack in some test data.
The takeaway here? Don't pollute your constructors with unrelated hacks. Bleh.

Unable to resolve service for type 'ClassLibrary.ApplicationDbContext' - an unhandled exception occurred

I have added a Class Library to my solution so that I can use Work Authentication on my ASP.Net Core site. I have been able to add a migration and update database from the PM console. However I am unable to use dotnet -ef. Upon running the site I am greeted with an unhandled exception occurred error and when researching the issue there is very little to be found, in order to solve it.
Any advice in order to remedy the situation would be much appreciated, I am happy to give extra detail, as I'm not sure whether the detail that I have give is sufficient.

ASP.NET MVC 5 with Entity Framework 6 to existing database with model binding for some tables

I have a SQL Server database with more than 50 tables. It was used for my web application written in ASP.NET. Now I write a new ASP.NET MVC 5 web application for new functions under the original web application folder. I create some models (about 10 tables) with code first migration enabled database.
Now I want to deploy the application to remote server. And the database connection still connect to the same existing SQL Server database.
But I always get the error :
Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NotSupportedException: Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
My code didn't have the models correlate to existing database tables. I don't want my code have the useless model and keep it simple. And I can't drop the existing database. Could any one tell me how can I do?
You have to replace your local server Name to IP address of your Live server
connection string='Data Source=ServerIP,portNumber\SQLEXPRESS2008R2;Initial Catalog=DBName;User ID=Sa;Password=123456789;integrated security=False;'
I have found the answer :
In Global.asax, I have added the line the Database.SetInitializer<...>.. It cause the error. Remove it as following , Thank you!
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//Database.SetInitializer<MyDBContext>(.....);
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}

fatal error 9001 while login into asp.net web site

This is the second time I got following error for my website:
Warning: Fatal error 9001 occurred at May 5 2012 1:16AM. Note the
error and time, and contact your system administrator.
I get this error while login to website. However, there is no any problem for connecting database or fetching records.
Last time I just took a backup and restore my database then this issue was resolved. But, I got again similar issue, now I want to know exact cause for this error.
I appreciate your reply.
Check SQL Server logs, seems to be an issue with log being full. "Last time I just took a backup and restore my database then this issue was resolved." seems to be database related. Check https://serverfault.com/questions/238394/diagnosing-microsoft-sql-server-error-9001-the-log-for-the-database-is-not-avai.

Getting LINQ to Firebird to work

I'm trying to generate an entity model from a Firebird database using the Entity Data Model Wizard, but it dies loading the data for the "Choose Your Database Objects" step with the error:
Microsoft Visual Studio
An error occurred while connecting to the
database. The database might be
unavailable. An exception of type
'System.Data.EntityCommandExecutionException'
occurred. The error message is: 'An
error occurred while executing the
command definition. See the inner
exception for details.
The inner exception caught was of type
'FirebirdSql.Data.FirebirdClient.FbException',
with this error message: 'Dynamic SQL
Error
SQL error code = -104
Token unknown - line 6, column 8
SELECT'.
The inner exception caught was of type
'FirebirdSql.Data.Common.IscException',
with this error message: 'Exception of
type
'FirebirdSql.Data.Common.IscException'
was thrown.'.'.
[ OK ]
I certainly believe it should work from this blog post on the ADO.Net team blog.
I'm able to browse tables and definitions using server explorer, so I think it's safe to discount connectivity/permissions issues, but I'm at a bit of a loss as to what else to check to get this working?
The blog post you speak about is beta version
the final release is on Jiri blog
or on Firebird
or here
According to the comment on this blog post, Firebird 1.5 is not support for LINQ to Firebird, even though it is supported version according to the Firebird website.

Categories

Resources