Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Entity Framework Core 6 Problem

Entity Framework Core 6 Problem

Scheduled Pinned Locked Moved C#
databasehelpasp-netsysadmin
24 Posts 3 Posters 82 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Kevin Marois

    I'm using EF 6 Core Code First. I'm trying to set up some basic code and I'm getting an exception at runtime. Here's my Context class:

    using Microsoft.EntityFrameworkCore;

    namespace EFCoreDBFirstExample.Models
    {
    public partial class ModelContext : DbContext
    {
    public virtual DbSet Departments { get; set; }
    public virtual DbSet Employees { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var connectionString = @"Server=MAROIS\_KEVIN\_1\\SQLEXPRESS;Database=Test;Trusted\_Connection=true;Encrypt=false;";
            optionsBuilder.UseSqlServer(connectionString, options => options.EnableRetryOnFailure());
        }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity(entity =>
            {
                entity.ToTable("Departments", "public");
    
                entity.HasKey(e => e.DepartmentId)
                      .HasName("DeptartmentId");
    
                entity.Property(e => e.DepartmentId)
                      .HasColumnName("DeptartmentId");
    
                entity.Property(e => e.DepartmentName)
                    .HasColumnName("DepartmentName")
                    .HasColumnType("varchar")
                    .HasMaxLength(30);
            });
    
            modelBuilder.Entity(entity =>
            {
                entity.ToTable("EmployeeName", "public");
    
                entity.HasKey(e => e.EmployeeId)
                      .HasName("EmployeeId");
    
                entity.Property(e => e.EmployeeId)
                      .HasColumnName("EmployeeId");
    
                entity.Property(e => e.EmployeeName)
                    .HasColumnName("EmployeeName")
                    .HasColumnType("varchar")
                    .HasMaxLength(30);
            });
        }
    }
    

    }

    Here's how I'm using it

    using EFCoreDBFirstExample.Models;

    using (var db = new ModelContext())
    {
    // Creating a new department and save it to the database
    var newDept = new Departments();
    newDept.DepartmentId = 1;
    newDept.DepartmentName = "Development";

    db.Departments.Add(newDept);
    var count = db.SaveChanges(); //<======================= ERROR HERE
    
    Console.WriteLine("{0} records saved to database", count);
    
    
    // Retrieve and display the data
    Console.WriteLine();
    Console.WriteLine("Departments:");
    foreach (var dept in db.Departments)
    
    D Online
    D Online
    Dave Kreskowiak
    wrote on last edited by
    #2

    Where did it get "kevin" from? That's the account you logged into Windows as. "Integrated Security" means use the Windows account the code is running as. The error message is blatantly obvious: "Cannot open database "Test" requested by the login. The login failed. Login failed for user 'MAROIS_KEVIN_1\kevin'." You SQL Server doesn't know who "kevin using a Windows Account" is. You have to go into SQL Server Manager to correctly setup a Windows Login account in your SQL Server Security and give it appropriate permissions to the database and tables as appropriate for your situation. If you haven't created the database yet and are relying on EF to do it for you, you have to give your account admin permissions to the SQL Server so YOU can create databases on the server.

    Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
    Dave Kreskowiak

    K 1 Reply Last reply
    0
    • D Dave Kreskowiak

      Where did it get "kevin" from? That's the account you logged into Windows as. "Integrated Security" means use the Windows account the code is running as. The error message is blatantly obvious: "Cannot open database "Test" requested by the login. The login failed. Login failed for user 'MAROIS_KEVIN_1\kevin'." You SQL Server doesn't know who "kevin using a Windows Account" is. You have to go into SQL Server Manager to correctly setup a Windows Login account in your SQL Server Security and give it appropriate permissions to the database and tables as appropriate for your situation. If you haven't created the database yet and are relying on EF to do it for you, you have to give your account admin permissions to the SQL Server so YOU can create databases on the server.

      Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
      Dave Kreskowiak

      K Offline
      K Offline
      Kevin Marois
      wrote on last edited by
      #3

      Yes, Kevin is my Windows login, but all my other apps use Trusted Connection without a user specified.

      connectionString="Server=MAROIS_KEVIN_1\SQLEXPRESS;Database=Jayhawk;Trusted_Connection=true;"

      I do have a user Kevin in SQL and I tried it with the password. I also just tried creating a new user and password and got the same error. Something else is wrong. Thanks

      If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

      D 1 Reply Last reply
      0
      • K Kevin Marois

        I'm using EF 6 Core Code First. I'm trying to set up some basic code and I'm getting an exception at runtime. Here's my Context class:

        using Microsoft.EntityFrameworkCore;

        namespace EFCoreDBFirstExample.Models
        {
        public partial class ModelContext : DbContext
        {
        public virtual DbSet Departments { get; set; }
        public virtual DbSet Employees { get; set; }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                var connectionString = @"Server=MAROIS\_KEVIN\_1\\SQLEXPRESS;Database=Test;Trusted\_Connection=true;Encrypt=false;";
                optionsBuilder.UseSqlServer(connectionString, options => options.EnableRetryOnFailure());
            }
        
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity(entity =>
                {
                    entity.ToTable("Departments", "public");
        
                    entity.HasKey(e => e.DepartmentId)
                          .HasName("DeptartmentId");
        
                    entity.Property(e => e.DepartmentId)
                          .HasColumnName("DeptartmentId");
        
                    entity.Property(e => e.DepartmentName)
                        .HasColumnName("DepartmentName")
                        .HasColumnType("varchar")
                        .HasMaxLength(30);
                });
        
                modelBuilder.Entity(entity =>
                {
                    entity.ToTable("EmployeeName", "public");
        
                    entity.HasKey(e => e.EmployeeId)
                          .HasName("EmployeeId");
        
                    entity.Property(e => e.EmployeeId)
                          .HasColumnName("EmployeeId");
        
                    entity.Property(e => e.EmployeeName)
                        .HasColumnName("EmployeeName")
                        .HasColumnType("varchar")
                        .HasMaxLength(30);
                });
            }
        }
        

        }

        Here's how I'm using it

        using EFCoreDBFirstExample.Models;

        using (var db = new ModelContext())
        {
        // Creating a new department and save it to the database
        var newDept = new Departments();
        newDept.DepartmentId = 1;
        newDept.DepartmentName = "Development";

        db.Departments.Add(newDept);
        var count = db.SaveChanges(); //<======================= ERROR HERE
        
        Console.WriteLine("{0} records saved to database", count);
        
        
        // Retrieve and display the data
        Console.WriteLine();
        Console.WriteLine("Departments:");
        foreach (var dept in db.Departments)
        
        S Offline
        S Offline
        Sam Hobbs
        wrote on last edited by
        #4

        Have you checked the file permissions for the database? I suppose that for a Trusted Connection that is not relevant. Can you open the database using that connection string in SSMS, or VS I suppose?

        K 1 Reply Last reply
        0
        • S Sam Hobbs

          Have you checked the file permissions for the database? I suppose that for a Trusted Connection that is not relevant. Can you open the database using that connection string in SSMS, or VS I suppose?

          K Offline
          K Offline
          Kevin Marois
          wrote on last edited by
          #5

          No I didn't check. There is no DB. EF is supposed to create ut

          If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

          1 Reply Last reply
          0
          • K Kevin Marois

            Yes, Kevin is my Windows login, but all my other apps use Trusted Connection without a user specified.

            connectionString="Server=MAROIS_KEVIN_1\SQLEXPRESS;Database=Jayhawk;Trusted_Connection=true;"

            I do have a user Kevin in SQL and I tried it with the password. I also just tried creating a new user and password and got the same error. Something else is wrong. Thanks

            If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

            D Online
            D Online
            Dave Kreskowiak
            wrote on last edited by
            #6

            When you created the "kevin" account in SQL Server Manager, did you tell it to use Windows Authentication or SQL Server Authentication?

            Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
            Dave Kreskowiak

            K 1 Reply Last reply
            0
            • D Dave Kreskowiak

              When you created the "kevin" account in SQL Server Manager, did you tell it to use Windows Authentication or SQL Server Authentication?

              Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
              Dave Kreskowiak

              K Offline
              K Offline
              Kevin Marois
              wrote on last edited by
              #7

              Windows Auth

              If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

              D 1 Reply Last reply
              0
              • K Kevin Marois

                Windows Auth

                If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                D Online
                D Online
                Dave Kreskowiak
                wrote on last edited by
                #8

                Next up, on the Server Roles tab, which roles have checkmarks next to them?

                Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                Dave Kreskowiak

                K 1 Reply Last reply
                0
                • D Dave Kreskowiak

                  Next up, on the Server Roles tab, which roles have checkmarks next to them?

                  Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                  Dave Kreskowiak

                  K Offline
                  K Offline
                  Kevin Marois
                  wrote on last edited by
                  #9

                  Public & SysAdmin

                  If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                  D 1 Reply Last reply
                  0
                  • K Kevin Marois

                    Public & SysAdmin

                    If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                    D Online
                    D Online
                    Dave Kreskowiak
                    wrote on last edited by
                    #10

                    OK, based on your answers, the login should work. I would go back to SQL Server Manager and create a new SQL account, password, and permissions of dbcreator and public. Change your connection string and remove TrustedConnection and put in the username and password of the account you create.

                    Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                    Dave Kreskowiak

                    K 1 Reply Last reply
                    0
                    • D Dave Kreskowiak

                      OK, based on your answers, the login should work. I would go back to SQL Server Manager and create a new SQL account, password, and permissions of dbcreator and public. Change your connection string and remove TrustedConnection and put in the username and password of the account you create.

                      Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                      Dave Kreskowiak

                      K Offline
                      K Offline
                      Kevin Marois
                      wrote on last edited by
                      #11

                      That's what I thought too. I have created a new login and still get the same error. Here's my Conn string

                      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                      {
                      var connectionString = @"Server=MAROIS_KEVIN_1\SQLEXPRESS;Database=Test;User Id=FatALbert;Password=AlbertIsFat!;;Encrypt=false;";
                      optionsBuilder.UseSqlServer(connectionString, options => options.EnableRetryOnFailure());
                      }

                      and the exception

                      Microsoft.EntityFrameworkCore.Storage.RetryLimitExceededException
                      HResult=0x80131500
                      Message=The maximum number of retries (6) was exceeded while executing database operations with 'SqlServerRetryingExecutionStrategy'. See the inner exception for the most recent failure.
                      Source=Microsoft.EntityFrameworkCore
                      StackTrace:
                      at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementation[TState,TResult](Func`3 operation, Func`3 verifySucceeded, TState state)
                      at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
                      at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
                      at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
                      at Program.

                      $(String[] args) in C:\Projects\SandBox\Learning\EF6Core\Database First\EFCoreDBFirstExample\Program.cs:line 11

                      This exception was originally thrown at this call stack:
                      [External Code]

                      Inner Exception 1:
                      SqlException: Cannot open database "Test" requested by the login. The login failed.
                      Login failed for user 'FatAlbert'.

                      I also tried creating the DB 'Test' first in SQL and assigning it to FatAlbert and the same exception. Again, I have other apps running on my Dev PC that don't use SQL Authentication and they connect just fine. So I has to be something with EF.

                      If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                      D 1 Reply Last reply
                      0
                      • K Kevin Marois

                        That's what I thought too. I have created a new login and still get the same error. Here's my Conn string

                        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                        {
                        var connectionString = @"Server=MAROIS_KEVIN_1\SQLEXPRESS;Database=Test;User Id=FatALbert;Password=AlbertIsFat!;;Encrypt=false;";
                        optionsBuilder.UseSqlServer(connectionString, options => options.EnableRetryOnFailure());
                        }

                        and the exception

                        Microsoft.EntityFrameworkCore.Storage.RetryLimitExceededException
                        HResult=0x80131500
                        Message=The maximum number of retries (6) was exceeded while executing database operations with 'SqlServerRetryingExecutionStrategy'. See the inner exception for the most recent failure.
                        Source=Microsoft.EntityFrameworkCore
                        StackTrace:
                        at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementation[TState,TResult](Func`3 operation, Func`3 verifySucceeded, TState state)
                        at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
                        at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
                        at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
                        at Program.

                        $(String[] args) in C:\Projects\SandBox\Learning\EF6Core\Database First\EFCoreDBFirstExample\Program.cs:line 11

                        This exception was originally thrown at this call stack:
                        [External Code]

                        Inner Exception 1:
                        SqlException: Cannot open database "Test" requested by the login. The login failed.
                        Login failed for user 'FatAlbert'.

                        I also tried creating the DB 'Test' first in SQL and assigning it to FatAlbert and the same exception. Again, I have other apps running on my Dev PC that don't use SQL Authentication and they connect just fine. So I has to be something with EF.

                        If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                        D Online
                        D Online
                        Dave Kreskowiak
                        wrote on last edited by
                        #12

                        Wait a minute. Did you put the connection string ONLY in the OnConfiguring method?

                        Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                        Dave Kreskowiak

                        K 1 Reply Last reply
                        0
                        • D Dave Kreskowiak

                          Wait a minute. Did you put the connection string ONLY in the OnConfiguring method?

                          Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                          Dave Kreskowiak

                          K Offline
                          K Offline
                          Kevin Marois
                          wrote on last edited by
                          #13

                          Yes. The examples I followed show it there. Isn't that what OnConfiguring does? A one time set up?

                          If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                          D 2 Replies Last reply
                          0
                          • K Kevin Marois

                            Yes. The examples I followed show it there. Isn't that what OnConfiguring does? A one time set up?

                            If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                            D Online
                            D Online
                            Dave Kreskowiak
                            wrote on last edited by
                            #14

                            This works differently from the older Entity Frameworks. The reason you're getting the login failure is because the database does not exist in SQLEXPRESS yet. You cannot create the database just by running the code you have, as is. You first have to enable migrations in the project, then create your first migration ("InitialCreate"). Once that is done, you can add the following line your program:

                            using (var db = new ModelContext())
                            {
                            // Update the database to the latest migration
                            db.Database.Migrate();

                            // Creating a new department and save it to the database
                            var newDept = new Departments();
                            newDept.DepartmentId = 1;
                            newDept.DepartmentName = "Development";
                            

                            I highly recommend AGAINST doing this! You are far better off managing and applying migrations using the EF command line tools! You can EASILY make a mistake that will destroy a production database just by running your code at the wrong time and with the wrong connection string! Migrations Overview - EF Core | Microsoft Learn[^] On top of that, there's a few mistakes in your code in your initial post above. For example, every DbSet should be DbSet<type> ...

                                public virtual DbSet Departments { get; set; }
                                public virtual DbSet Employees { get; set; }
                            

                            ...and there are mispellings in your modelBuilder code, like

                            entity.ToTable(**"Employees"**, "public");
                            

                            Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                            Dave Kreskowiak

                            K 2 Replies Last reply
                            0
                            • K Kevin Marois

                              Yes. The examples I followed show it there. Isn't that what OnConfiguring does? A one time set up?

                              If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                              D Online
                              D Online
                              Dave Kreskowiak
                              wrote on last edited by
                              #15

                              In a production environment, you would NEVER hardcode a connection string. This would prevent you from developing against a dev version of the database and testing code and migrations without impacting the production database. Read the entire section on Migrations, not just the Overview: Migrations Overview - EF Core | Microsoft Learn[^]

                              Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                              Dave Kreskowiak

                              K 1 Reply Last reply
                              0
                              • D Dave Kreskowiak

                                In a production environment, you would NEVER hardcode a connection string. This would prevent you from developing against a dev version of the database and testing code and migrations without impacting the production database. Read the entire section on Migrations, not just the Overview: Migrations Overview - EF Core | Microsoft Learn[^]

                                Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                                Dave Kreskowiak

                                K Offline
                                K Offline
                                Kevin Marois
                                wrote on last edited by
                                #16

                                Ya, I Put it there just for testing. Thanks for all your help

                                If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                                1 Reply Last reply
                                0
                                • D Dave Kreskowiak

                                  This works differently from the older Entity Frameworks. The reason you're getting the login failure is because the database does not exist in SQLEXPRESS yet. You cannot create the database just by running the code you have, as is. You first have to enable migrations in the project, then create your first migration ("InitialCreate"). Once that is done, you can add the following line your program:

                                  using (var db = new ModelContext())
                                  {
                                  // Update the database to the latest migration
                                  db.Database.Migrate();

                                  // Creating a new department and save it to the database
                                  var newDept = new Departments();
                                  newDept.DepartmentId = 1;
                                  newDept.DepartmentName = "Development";
                                  

                                  I highly recommend AGAINST doing this! You are far better off managing and applying migrations using the EF command line tools! You can EASILY make a mistake that will destroy a production database just by running your code at the wrong time and with the wrong connection string! Migrations Overview - EF Core | Microsoft Learn[^] On top of that, there's a few mistakes in your code in your initial post above. For example, every DbSet should be DbSet<type> ...

                                      public virtual DbSet Departments { get; set; }
                                      public virtual DbSet Employees { get; set; }
                                  

                                  ...and there are mispellings in your modelBuilder code, like

                                  entity.ToTable(**"Employees"**, "public");
                                  

                                  Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                                  Dave Kreskowiak

                                  K Offline
                                  K Offline
                                  Kevin Marois
                                  wrote on last edited by
                                  #17

                                  Thanks alot!

                                  If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                                  1 Reply Last reply
                                  0
                                  • D Dave Kreskowiak

                                    This works differently from the older Entity Frameworks. The reason you're getting the login failure is because the database does not exist in SQLEXPRESS yet. You cannot create the database just by running the code you have, as is. You first have to enable migrations in the project, then create your first migration ("InitialCreate"). Once that is done, you can add the following line your program:

                                    using (var db = new ModelContext())
                                    {
                                    // Update the database to the latest migration
                                    db.Database.Migrate();

                                    // Creating a new department and save it to the database
                                    var newDept = new Departments();
                                    newDept.DepartmentId = 1;
                                    newDept.DepartmentName = "Development";
                                    

                                    I highly recommend AGAINST doing this! You are far better off managing and applying migrations using the EF command line tools! You can EASILY make a mistake that will destroy a production database just by running your code at the wrong time and with the wrong connection string! Migrations Overview - EF Core | Microsoft Learn[^] On top of that, there's a few mistakes in your code in your initial post above. For example, every DbSet should be DbSet<type> ...

                                        public virtual DbSet Departments { get; set; }
                                        public virtual DbSet Employees { get; set; }
                                    

                                    ...and there are mispellings in your modelBuilder code, like

                                    entity.ToTable(**"Employees"**, "public");
                                    

                                    Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                                    Dave Kreskowiak

                                    K Offline
                                    K Offline
                                    Kevin Marois
                                    wrote on last edited by
                                    #18

                                    OK, so I went through the Migrations Oerview and installed the necessary packages. I then ran Add Migration and Update Database. Now I get this

                                    Applying migration '20221127185110_Initial'.
                                    Failed executing DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
                                    IF SCHEMA_ID(N'public') IS NULL EXEC(N'CREATE SCHEMA [public];');
                                    Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named 'public' in the database.
                                    CREATE SCHEMA failed due to previous errors.
                                    at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                                    at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                                    at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
                                    at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
                                    at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
                                    at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
                                    at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
                                    at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
                                    at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
                                    at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
                                    at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
                                    at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
                                    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
                                    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
                                    at Microsoft.EntityFrameworkC

                                    D 1 Reply Last reply
                                    0
                                    • K Kevin Marois

                                      OK, so I went through the Migrations Oerview and installed the necessary packages. I then ran Add Migration and Update Database. Now I get this

                                      Applying migration '20221127185110_Initial'.
                                      Failed executing DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
                                      IF SCHEMA_ID(N'public') IS NULL EXEC(N'CREATE SCHEMA [public];');
                                      Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named 'public' in the database.
                                      CREATE SCHEMA failed due to previous errors.
                                      at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                                      at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                                      at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
                                      at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
                                      at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
                                      at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
                                      at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
                                      at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
                                      at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
                                      at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
                                      at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
                                      at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
                                      at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
                                      at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
                                      at Microsoft.EntityFrameworkC

                                      D Online
                                      D Online
                                      Dave Kreskowiak
                                      wrote on last edited by
                                      #19

                                      Change "public" to "dbo" in your code. Where did you find this tutorial you're following? The problem with Linq-To-Sql is that it is a dead product and no longer under development.

                                      Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                                      Dave Kreskowiak

                                      K 2 Replies Last reply
                                      0
                                      • D Dave Kreskowiak

                                        Change "public" to "dbo" in your code. Where did you find this tutorial you're following? The problem with Linq-To-Sql is that it is a dead product and no longer under development.

                                        Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                                        Dave Kreskowiak

                                        K Offline
                                        K Offline
                                        Kevin Marois
                                        wrote on last edited by
                                        #20

                                        Dave Kreskowiak wrote:

                                        Where did you find this tutorial you're following?

                                        I have the book I mentioned in my other reply, as well as a couple of YouTube vids I followed.

                                        Dave Kreskowiak wrote:

                                        The problem with Linq-To-Sql is that it is a dead product and no longer under development.

                                        Yup. Thats why I'm doing this.

                                        If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                                        1 Reply Last reply
                                        0
                                        • D Dave Kreskowiak

                                          Change "public" to "dbo" in your code. Where did you find this tutorial you're following? The problem with Linq-To-Sql is that it is a dead product and no longer under development.

                                          Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                                          Dave Kreskowiak

                                          K Offline
                                          K Offline
                                          Kevin Marois
                                          wrote on last edited by
                                          #21

                                          OK, I think I have this now. I did the migration and update, and the DB was created and Department and Employee tables added. Next, I added a Companies entity, linked it to Departments, and ran

                                          dotnet ef migrations add AddCompanies
                                          dotnet ef database update

                                          and the Db is now up to date. So I need to run these 2 commands each time I make a change?

                                          If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                                          D 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups