1
  static void Main(string[] args)
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<KekDB>());
            char a;
            string name, family;
            int age;
            using (KekDB db=new KekDB())
            {
                //try
                //{
                    Console.WriteLine("Input char");
                    a=Convert.ToChar(Console.ReadLine());
                    Console.WriteLine("Input age");
                    age = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("Input name");
                    name =Convert.ToString(Console.ReadLine());
                    Console.WriteLine("Input family");
                    family = Convert.ToString(Console.ReadLine());
                    var cl =new  ClassRoom(a);
                    db.ClassTable.Add(cl);
                    db.SaveChanges();
                    var pr = new Person(name,family,age,cl);
                    db.PersonTable.Add(pr);
                    db.SaveChanges();
                }
                //catch (Exception)
                //{

                //    Console.WriteLine("Error");
                //}
           // }
            Console.WriteLine("Input smt");
            Console.ReadKey();
        }
    }
 public class ClassRoom
    {
        [Key]
        public char letter { get; set; }
        public ICollection<Person> persons { get; set; }
        public ClassRoom() { }
        public ClassRoom(char a)
        {
            letter = a;
            persons = new List<Person>();
        }
    }
 public class Person
    {
        public int personId { get; set; }
        public string FirstName{get;set;}
        public string LastName { get; set; }
        public int Age { get; set; }
        public ClassRoom clas { get; set; }
        public Person() { }
         public Person(string firstName,string lastName,int Age,ClassRoom cl)
        {
            FirstName = firstName;
            LastName = lastName;
            this.Age = Age;
            clas = cl;
        }
    }

Необработанное исключение: System.Data.SqlClient.SqlException: При установлении соединения с SQL Ser ver произошла ошибка, связанная с сетью или с определенным экземпляром. Сервер не найден или недосту пен. Убедитесь, что имя экземпляра указано правильно и что на SQL Server разрешены удаленные соедине ния. (provider: SQL Network Interfaces, error: 50 - Произошла ошибка Local Database Runtime.Невозмож но создать автоматический экземпляр. Дополнительные сведения об ошибке см. в журнале событий приложе ний Windows. ) в System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConn ectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, S ecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOpt ions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTran sientFaultHandling) в System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConn ectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConne ction, DbConnectionOptions userOptions) в System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbCo nnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) в System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionO ptions userOptions, DbConnectionInternal oldConnection) в System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnec tionOptions userOptions, DbConnectionInternal oldConnection) в System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 wa itForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOption s userOptions, DbConnectionInternal& connection) в System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompl etionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) в System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, Ta skCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbC onnectionInternal& connection) в System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConne ction, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions user Options) в System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbC onnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) в System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) в System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) в System.Data.SqlClient.SqlConnection.Open() в System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.b__36(DbConnection t, DbConnectionInterceptionContext c) в System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TIntercept ionContext](TTarget target, Action2 operation, TInterceptionContext interceptionContext, Action3 e xecuting, Action3 executed) в System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connect ion, DbInterceptionContext interceptionContext) в System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.b__32() в System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.b__0() в System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation) в System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) в System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Ac tion1 act) в System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnecti on, Action1 act) в System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1 commandTim eout, DbConnection sqlConnection, String createDatabaseScript) в System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Null able1 commandTimeout, StoreItemCollection storeItemCollection) в System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nulla ble1 commandTimeout, StoreItemCollection storeItemCollection) в System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase() в System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) в System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)

в System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) в System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Fun c3 createMigrator, ObjectContext objectContext) в System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, Databas eExistenceState existenceState) в System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) в System.Data.Entity.DropCreateDatabaseAlways1.InitializeDatabase(TContext context) в System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf1.<CreateInitializationAction>b_ _e() в System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) в System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() в System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c) в System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input) в System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action) в System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() в System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) в System.Data.Entity.Internal.Linq.InternalSet1.Initialize() в System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext() в System.Data.Entity.Internal.Linq.InternalSet1.AddRange(IEnumerable entities) в System.Data.Entity.DbSet1.AddRange(IEnumerable1 entities) в _002_1_to_M.Program.Main(String[] args) в D:\Видео\entity framework\Entity Framework 6\002_Fund amentals EF_6\003_Relations\002_1_to_M\Program.cs:строка 23 Для продолжения нажмите любую клавишу . . .

7
  • Сообщения об ошибках лучше включить в виде текста. 21 дек 2017 в 14:17
  • Как это сделать?
    – Nikita
    21 дек 2017 в 14:20
  • Нажать правой кнопкой в окне консоли. В выпадающем меню выбрать пункт «Выделить все» («Select All»). Нажать Enter после чего весь вывод вставить в текст вопроса (правится по ссылке «править» под текстом вопроса). 21 дек 2017 в 14:22
  • В сообщении говорится о том, что провайдер не смог достучаться до экземпляра SQL Server. Проверьте строку подключения. 21 дек 2017 в 15:29
  • а что здесь мб не так?(LocalDb)\MSSQLLocalDB
    – Nikita
    21 дек 2017 в 15:50

1 ответ 1

2

Ошибка очевидна: "Сервер не найден или недоступен.". Вам необходимо проверить строку соединения след.образом.

1) Нам нужно отрыть окно SQL Server Object Explorer

меню открытия окна

2) Найти наш сервер и прав.кликом выбрать пункт свойства

выбор пункта меню

3) В окне свойств найти раздел Connection string выделить значение этой

раздел строки соединения с сервером

строки и скопировать и вставить в нужное место вашей программы.

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.