Shittu Joseph Olugbenga
Shittu Joseph Olugbenga

Reputation: 6476

Entity framework 6.1.3 cannot create Database

I created a web application with entity framework code-first version 4. i had the requirement to manually create the database on a button click on an Installation page. I used the code below to achieve it.

public class UnitOfWork
{
    private readonly MyDataContext _context;
    public UnitOfWork(MyDataContext context)
    {
        this._context = context;
    }
    private static readonly Object syncObj = new Object();
    public void DbInit(bool force = false)
    {
        lock (syncObj)
        {
            if (_context.Database.Exists()) return;
            System.Data.Entity.Database.SetInitializer<MyDataContext>(new MigrateDatabaseToLatestVersion<MyDataContext, Configuration>());
            _context.Database.Initialize(force);
            ...

        }
    }
}

The Problem

The problem is I updated to Entity Framework 6.1.3 and this code does not work again. I am now getting the error: Cannot open database "TesterDB" requested by the login. The login failed. Login failed for user 'sa'.

My Understanding

1) I know the system is trying to access the database when it does not exist. I really want the database to be created on click of the button, hence, it would not have been created at that point.

2) My credentials are correct. I logged in to SQL Management studio with the same credentials. Infact, the credentials work when database has been created.

I am in dire need of this solution as my client is currently mounting pressure on me. Your help is highly appreciated.

UPDATE 1

I changed

System.Data.Entity.Database.SetInitializer<MyDataContext>(new MigrateDatabaseToLatestVersion<MyDataContext, Configuration>());

to

System.Data.Entity.Database.SetInitializer(new CreateDatabaseIfNotExists<DataContext>());

and

System.Data.Entity.Database.SetInitializer(new DropCreateDatabaseAlways<DataContext>());

and the error still keeps coming.

Also i know that the user sa has access to the database as i could access it with the user when the database is finally created. As a matter of fact, i created another user and the problem still persist.

UPDATE 2

The error occurred at _context.Database.Initialize(force);

Upvotes: 2

Views: 1110

Answers (1)

I don't think the problem is EF because the exception is clear.

There are 2 common mistakes for the sa User on the SQL Database Engine:

  1. User is not allowed to login to Database Engine. Enable in Settings for User.

enter image description here

  1. Database Engine only allows Windows-Login. Change it in the server Properties

enter image description here

Hope it helps!

Upvotes: 1

Related Questions