Can't access Azure sql with EF Core - Code first, but can with database first

0

so as the title suggests.

I have done the following:

Created simple models (c# classes). Added Nugget packages: - Microsoft.EntityFrameworkCore.Design(3.1.3) - Microsoft.EntityFrameworkCore.SqlServer(3.1.3)

I Have added the following context:

namespace PriceCalendarService.Data
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options) { }
        public DbSet<Item> Items { get; set; }
        public DbSet<CustomerType> CustomerTypes { get; set; }
        public DbSet<Group> Groups { get; set; }
        public DbSet<ItemDay> ItemDays { get; set; }
        public DbSet<ItemPriceAndCurrencyResponse> ItemsPriceAndCurrencyResponses { get; set; }
    }
}

In appsettings.json I have registered the connectionString. I have tried quite a lot of different format options for the connection string, seeing as the one provided by azure has not worked.

When i run dotnet ef migrations add InitialCreate, both the migration + the data context model snapshot are created no problem:

namespace PriceCalendarService.Migrations
{
    public partial class InitialCreate : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "CustomerTypes",
                columns: table => new
                {
                    id = table.Column<Guid>(nullable: false),
                    Description = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_CustomerTypes", x => x.id);
                });

            migrationBuilder.CreateTable(
                name: "ItemsPriceAndCurrencyResponses",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Currency = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ItemsPriceAndCurrencyResponses", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Groups",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Description = table.Column<string>(nullable: true),
                    CustomerTypeid = table.Column<Guid>(nullable: true),
                    ItemPriceAndCurrencyResponseId = table.Column<int>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Groups", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Groups_CustomerTypes_CustomerTypeid",
                        column: x => x.CustomerTypeid,
                        principalTable: "CustomerTypes",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_Groups_ItemsPriceAndCurrencyResponses_ItemPriceAndCurrencyResponseId",
                        column: x => x.ItemPriceAndCurrencyResponseId,
                        principalTable: "ItemsPriceAndCurrencyResponses",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateTable(
                name: "Items",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Name = table.Column<string>(nullable: true),
                    Price = table.Column<decimal>(nullable: false),
                    GroupId = table.Column<int>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Items", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Items_Groups_GroupId",
                        column: x => x.GroupId,
                        principalTable: "Groups",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateTable(
                name: "ItemDays",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Date = table.Column<DateTime>(nullable: false),
                    Price = table.Column<decimal>(nullable: false),
                    Priority = table.Column<string>(nullable: true),
                    PricePackage = table.Column<string>(nullable: true),
                    CustomerTypeid = table.Column<Guid>(nullable: true),
                    ItemId = table.Column<Guid>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ItemDays", x => x.Id);
                    table.ForeignKey(
                        name: "FK_ItemDays_CustomerTypes_CustomerTypeid",
                        column: x => x.CustomerTypeid,
                        principalTable: "CustomerTypes",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_ItemDays_Items_ItemId",
                        column: x => x.ItemId,
                        principalTable: "Items",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateIndex(
                name: "IX_Groups_CustomerTypeid",
                table: "Groups",
                column: "CustomerTypeid");

            migrationBuilder.CreateIndex(
                name: "IX_Groups_ItemPriceAndCurrencyResponseId",
                table: "Groups",
                column: "ItemPriceAndCurrencyResponseId");

            migrationBuilder.CreateIndex(
                name: "IX_ItemDays_CustomerTypeid",
                table: "ItemDays",
                column: "CustomerTypeid");

            migrationBuilder.CreateIndex(
                name: "IX_ItemDays_ItemId",
                table: "ItemDays",
                column: "ItemId");

            migrationBuilder.CreateIndex(
                name: "IX_Items_GroupId",
                table: "Items",
                column: "GroupId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "ItemDays");

            migrationBuilder.DropTable(
                name: "Items");

            migrationBuilder.DropTable(
                name: "Groups");

            migrationBuilder.DropTable(
                name: "CustomerTypes");

            migrationBuilder.DropTable(
                name: "ItemsPriceAndCurrencyResponses");
        }
    }
}

And the snapshot:

namespace PriceCalendarService.Migrations
{
    [DbContext(typeof(DataContext))]
    partial class DataContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "3.1.3")
                .HasAnnotation("Relational:MaxIdentifierLength", 128)
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("PriceCalendarService.Models.CustomerType", b =>
                {
                    b.Property<Guid>("id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("uniqueidentifier");

                    b.Property<string>("Description")
                        .HasColumnType("nvarchar(max)");

                    b.HasKey("id");

                    b.ToTable("CustomerTypes");
                });

            modelBuilder.Entity("PriceCalendarService.Models.Group", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<Guid?>("CustomerTypeid")
                        .HasColumnType("uniqueidentifier");

                    b.Property<string>("Description")
                        .HasColumnType("nvarchar(max)");

                    b.Property<int?>("ItemPriceAndCurrencyResponseId")
                        .HasColumnType("int");

                    b.HasKey("Id");

                    b.HasIndex("CustomerTypeid");

                    b.HasIndex("ItemPriceAndCurrencyResponseId");

                    b.ToTable("Groups");
                });

            modelBuilder.Entity("PriceCalendarService.Models.Item", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("uniqueidentifier");

                    b.Property<int?>("GroupId")
                        .HasColumnType("int");

                    b.Property<string>("Name")
                        .HasColumnType("nvarchar(max)");

                    b.Property<decimal>("Price")
                        .HasColumnType("decimal(18,2)");

                    b.HasKey("Id");

                    b.HasIndex("GroupId");

                    b.ToTable("Items");
                });

            modelBuilder.Entity("PriceCalendarService.Models.ItemDay", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<Guid?>("CustomerTypeid")
                        .HasColumnType("uniqueidentifier");

                    b.Property<DateTime>("Date")
                        .HasColumnType("datetime2");

                    b.Property<Guid?>("ItemId")
                        .HasColumnType("uniqueidentifier");

                    b.Property<decimal>("Price")
                        .HasColumnType("decimal(18,2)");

                    b.Property<string>("PricePackage")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("Priority")
                        .HasColumnType("nvarchar(max)");

                    b.HasKey("Id");

                    b.HasIndex("CustomerTypeid");

                    b.HasIndex("ItemId");

                    b.ToTable("ItemDays");
                });

            modelBuilder.Entity("PriceCalendarService.Models.ItemPriceAndCurrencyResponse", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<string>("Currency")
                        .HasColumnType("nvarchar(max)");

                    b.HasKey("Id");

                    b.ToTable("ItemsPriceAndCurrencyResponses");
                });

            modelBuilder.Entity("PriceCalendarService.Models.Group", b =>
                {
                    b.HasOne("PriceCalendarService.Models.CustomerType", null)
                        .WithMany("Groups")
                        .HasForeignKey("CustomerTypeid");

                    b.HasOne("PriceCalendarService.Models.ItemPriceAndCurrencyResponse", null)
                        .WithMany("Groups")
                        .HasForeignKey("ItemPriceAndCurrencyResponseId");
                });

            modelBuilder.Entity("PriceCalendarService.Models.Item", b =>
                {
                    b.HasOne("PriceCalendarService.Models.Group", null)
                        .WithMany("Items")
                        .HasForeignKey("GroupId");
                });

            modelBuilder.Entity("PriceCalendarService.Models.ItemDay", b =>
                {
                    b.HasOne("PriceCalendarService.Models.CustomerType", "CustomerType")
                        .WithMany()
                        .HasForeignKey("CustomerTypeid");

                    b.HasOne("PriceCalendarService.Models.Item", null)
                        .WithMany("ItemDays")
                        .HasForeignKey("ItemId");
                });
#pragma warning restore 612, 618
        }
    }
}

The problem occurs when i run 'dotnet ef database update'.

Before you mention it, I am 100% sure credentials are correct, firewall setting on azure allows my ip, etc. I have successfully connected to the database with SSMS. Furthermore, the database I did with 'database first' scaffolding, is on the same server, and works fine.

I get the following in powershell (ef tools are globally installed):

Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user 'MY_USER_NAME'.
   at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at Microsoft.Data.SqlClient.SqlConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:fb26ab6e-4c8f-4adc-badb-0aefb5041852
Error Number:18456,State:1,Class:14
Login failed for user 'MY_USER_NAME'.

, where MY_USER_NAME is my actual user name of course.

I have tried many connectionstrings, as i suspect it is there the problem is (the one provided for azure actually didnt work for my other project either).

From azure: Server=tcp:SERVER_NAME,1433;Initial Catalog=PriceCalendarService;Persist Security Info=False;User ID=USERID;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;

From other source that I use on the database first project: Data Source=SERVER;Initial Catalog:DB_NAME;User ID=USER_ID;Password=PASSWORD;Connect Timeout=60;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False

I'm at a total loss, I have tried all i could find, does anyone have an idea what I'm doing wrong? Any input would be greatly appreciated.

Lastly, sorry if the post is not after specifications - it's my first post of stackoverflow.

asp.net
entity-framework
entity-framework-core
azure-sql-database
azure-sql-server
asked on Stack Overflow Apr 21, 2020 by Oskar

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0