Невозможно получить доступ к Azure sql с EF Core - сначала код, но можно сначала с базой данных - PullRequest
0 голосов
/ 21 апреля 2020

, как следует из названия.

Я сделал следующее:

Создал простые модели (c# классы). Добавлены пакеты Nugget: - Microsoft.EntityFrameworkCore.Design (3.1.3) - Microsoft.EntityFrameworkCore.SqlServer (3.1.3)

Я добавил следующий контекст:

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; }
    }
}

В настройках приложения . json Я зарегистрировал строку подключения. Я перепробовал довольно много разных форматов для строки подключения, видя, что тот, который предоставлен azure, не работал.

Когда я запускаю do tnet ef migrations добавьте InitialCreate, оба миграции + моментальный снимок модели контекста данных создается без проблем:

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");
        }
    }
}

И снимок:

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
        }
    }
}

Проблема возникает, когда я запускаю 'do tnet ef update database'.

Прежде чем вы упомянете об этом, я на 100% уверен, что учетные данные верны, настройка брандмауэра на azure разрешает мой ip, et c. Я успешно подключился к базе данных с помощью SSMS. Кроме того, база данных, которую я создал с помощью лесов 'database first', находится на том же сервере и работает нормально.

В PowerShell получено следующее (инструменты ef установлены глобально):

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'.

, где MY_USER_NAME - это мое действительное имя пользователя, конечно.

Я перепробовал много строк подключения, так как подозреваю, что есть проблема (та, которая предусмотрена для azure, фактически не работала и для моего другого проекта). ).

От azure: Сервер = tcp: SERVER_NAME, 1433; Начальный каталог = PriceCalendarService; Постоянная информация о безопасности = Ложь; ID пользователя = USERID; Пароль = {your_password}; MultipleActiveResultSets = False; Encrypt = True; TrustServerCertificate = Ложь; Время ожидания подключения = 30;

Из другого источника, который я использую в первом проекте базы данных: Источник данных = SERVER; Начальный каталог: DB_NAME; Идентификатор пользователя = USER_ID; Пароль = ПАРОЛЬ; Время ожидания подключения = 60; Encrypt = True; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False

Я в полной растерянности, я перепробовал все, что смог найти, у кого-нибудь есть идея, что я делаю неправильно? Любая информация будет принята с благодарностью.

Наконец, извините, если пост не соответствует спецификациям - это мой первый пост из stackoverflow.

...