c# – Unable to connect to SQL Server database – C # MVC

Question:

I am writing an application in ASP.NET MVC.

It was necessary to display a list of all registered users. I decided to use Membership.GetAllUsers() to display the list, but I get an exception:

A network or instance-specific error occurred while establishing a connection to SQL Server. Server not found or unavailable. Make sure the instance name is correct and that remote connections are allowed on the SQL Server. (provider: SQL Network Interfaces, error: 26 – Error finding the specified server or instance)

What code do you need? The localdb database, I'm trying to get a list of users through Membership.GetAllUsers() in the controller and pass it to the view. There are tables in the database, the connection is fine if you connect through the DatabaseContext db = new DatabaseContext() object DatabaseContext db = new DatabaseContext() . But this way I can't get user roles.

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-SoftwareDevelopmentCustom;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-SoftwareDevelopmentCustom.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>

Code:

   using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Threading;
    using System.Web.Mvc;
    using WebMatrix.WebData;
    using SoftwareDevelopmentCustom.Models;
    using System.Web.Security;

    namespace SoftwareDevelopmentCustom.Filters
    {
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
        public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
        {
            private static SimpleMembershipInitializer _initializer;

            private static object _initializerLock = new object();

            private static bool _isInitialized;

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                // Инициализация ASP.NET Simple Membership происходит один раз при старте приложения
                LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
            }

            private class SimpleMembershipInitializer // определение класса инициализатора
            {
                public SimpleMembershipInitializer()
                {
                    Database.SetInitializer<DatabaseContext>(null);

                    try
                    {
                        using (var context = new DatabaseContext())
                        {
                            if (!context.Database.Exists())
                            {
                                // Создание базы данных SimpleMembership без применения миграции Entity Framework
                                ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                            }
                        }
                        // Настройка  ASP.NET Simple Membership
                        // 1 параметр - имя строки подключения к базе данных.
                        // 2 параметр - таблица, которая содержит информацию о пользователях
                        // 3 параметр - имя колонки в таблице, которая отвечает за хранение логина
                        // 4 параметр - autoCreateTables автоматическое создание таблиц если они не существуют в базе
                        WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

                        SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider;
                        SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider;


                        // Проверка наличия роли Admin
                        if (!roles.RoleExists("Admin")) 
                        {
                            roles.CreateRole("Admin");
                        }
                        // Поиск пользователя с логином admin
                        if (membership.GetUser("admin", false) == null)
                        {
                            membership.CreateUserAndAccount("admin", "qwe123"); // создание пользователя
                            roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admin" }); // установка роли для пользователя
                        }

                    }
                    catch (Exception ex)
                    {
                        throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                    }
                }
            }
        }
    }

Answer:

The problem is not in the code, the problem is in the connection string.

using (var context = new DatabaseContext())
{
}

This code does not actually create a connection. The connection is made at the time of the first request, i.e. you have it

if (!context.Database.Exists()){}

Try to connect to the base, which is specified in your DefaultConnection from Visual Studio Server Explorer.

Scroll to Top