Модель, поддерживающая контекст '...', изменилась с момента создания базы данных. - PullRequest
0 голосов
/ 13 июля 2020

У меня есть также enablemigration = true. Но у меня есть определение таблицы для сохранения всех полей формы. Он продолжает вызывать эту ошибку. «System.InvalidOperationException HResult = 0x80131509 Message = Модель, поддерживающая контекст 'eNtsaRegistration', изменилась с момента создания базы данных. Рассмотрите возможность использования первой миграции кода для обновления базы данных (http://go.microsoft.com/fwlink/?LinkId=238269)». Я хочу добиться того, чтобы все поля из формы, которую они должны отправить, было отправлено в определение моей таблицы. Я могу получить список всех стран при загрузке формы и выбрать их. Что именно мне не хватает?

        // Migration Folder. 
        using System;
        using Microsoft.EntityFrameworkCore.Migrations;
        
        namespace eNtsaRegistrationTraining.Migrations
        {
            public partial class eNtsaRegistration : Migration
            {
                protected override void Up(MigrationBuilder migrationBuilder)
                {
                    migrationBuilder.CreateTable(
                        name: "__MigrationHistory",
                        columns: table => new
                        {
                            MigrationId = table.Column<string>(maxLength: 150, nullable: false),
                            ContextKey = table.Column<string>(maxLength: 300, nullable: false),
                            Model = table.Column<byte[]>(nullable: false),
                            ProductVersion = table.Column<string>(maxLength: 32, nullable: false)
                        },
                        constraints: table =>
                        {
                            table.PrimaryKey("PK_dbo.__MigrationHistory", x => new { x.MigrationId, x.ContextKey });
                        });
        
                    migrationBuilder.CreateTable(
                        name: "AspNetRoles",
                        columns: table => new
                        {
                            Id = table.Column<string>(maxLength: 128, nullable: false),
                            Name = table.Column<string>(maxLength: 256, nullable: false),
                            DisplayName = table.Column<string>(nullable: true),
                            Description = table.Column<string>(nullable: true)
                        },
                        constraints: table =>
                        {
                            table.PrimaryKey("PK_AspNetRoles", x => x.Id);
                        });
        
                    migrationBuilder.CreateTable(
                        name: "AspNetUsers",
                        columns: table => new
                        {
                            Id = table.Column<string>(maxLength: 128, nullable: false),
                            FirstName = table.Column<string>(nullable: true),
                            LastName = table.Column<string>(nullable: true),
                            LocalAddress = table.Column<string>(nullable: true),
                            PermanentAddress = table.Column<string>(nullable: true),
                            Email = table.Column<string>(maxLength: 256, nullable: true),
                            EmailConfirmed = table.Column<bool>(nullable: false),
                            PasswordHash = table.Column<string>(nullable: true),
                            SecurityStamp = table.Column<string>(nullable: true),
                            PhoneNumber = table.Column<string>(nullable: true),
                            PhoneNumberConfirmed = table.Column<bool>(nullable: false),
                            TwoFactorEnabled = table.Column<bool>(nullable: false),
                            LockoutEndDateUtc = table.Column<DateTime>(type: "datetime", nullable: true),
                            LockoutEnabled = table.Column<bool>(nullable: false),
                            AccessFailedCount = table.Column<int>(nullable: false),
                            UserName = table.Column<string>(maxLength: 256, nullable: false),
                            ProfilePicPath = table.Column<string>(nullable: true)
                        },
                        constraints: table =>
                        {
                            table.PrimaryKey("PK_AspNetUsers", x => x.Id);
                        });
        
                    migrationBuilder.CreateTable(
                        name: "Dietary",
                        columns: table => new
                        {
                            None = table.Column<string>(maxLength: 10, nullable: false),
                            Vegetarian = table.Column<string>(maxLength: 10, nullable: true),
                            Vegan = table.Column<string>(maxLength: 10, nullable: true),
                            Halaal = table.Column<string>(maxLength: 10, nullable: true),
                            Other = table.Column<string>(maxLength: 50, nullable: true)
                        },
                        constraints: table =>
                        {
                            table.PrimaryKey("PK_Dietary", x => x.None);
                        });
        
                    migrationBuilder.CreateTable(
                        name: "Locations",
                        columns: table => new
                        {
                            Name = table.Column<string>(maxLength: 50, nullable: false),
                            Latitute = table.Column<decimal>(type: "numeric(18, 0)", nullable: true),
                            Longitute = table.Column<decimal>(type: "numeric(18, 0)", nullable: true),
                            Description = table.Column<string>(nullable: true)
                        },
                        constraints: table =>
                        {
                            table.PrimaryKey("PK_Locations", x => x.Name);
                        });
        
                    migrationBuilder.CreateTable(
                        name: "TbTrainingForm",
                        columns: table => new
                        {
                            ID = table.Column<int>(nullable: true),
                            Title = table.Column<string>(maxLength: 50, nullable: false),
                            FirstName = table.Column<string>(maxLength: 50, nullable: false),
                            LastName = table.Column<string>(maxLength: 50, nullable: false),
                            Position = table.Column<string>(maxLength: 50, nullable: false),
                            Company = table.Column<string>(maxLength: 50, nullable: false),
                            StreetAddress = table.Column<string>(nullable: false),
                            StreetAddressLine = table.Column<string>(nullable: false),
                            City = table.Column<string>(maxLength: 50, nullable: false),
                            StateProvince = table.Column<string>(name: "State/Province", maxLength: 50, nullable: false),
                            ZipCode = table.Column<int>(name: "Zip/Code", nullable: false),
                            Email = table.Column<string>(maxLength: 50, nullable: false),
                            CellNumber = table.Column<int>(nullable: false),
                            DietaryRequirement = table.Column<string>(maxLength: 50, nullable: false)
                        },
                        constraints: table =>
                        {
                        });
        
                    migrationBuilder.CreateTable(
                        name: "AspNetUserClaims",
                        columns: table => new
                        {
                            Id = table.Column<int>(nullable: false)
                                .Annotation("SqlServer:Identity", "1, 1"),
                            UserId = table.Column<string>(maxLength: 128, nullable: false),
                            ClaimType = table.Column<string>(nullable: true),
                            ClaimValue = table.Column<string>(nullable: true)
                        },
                        constraints: table =>
                        {
                            table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
                            table.ForeignKey(
                                name: "FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId",
                                column: x => x.UserId,
                                principalTable: "AspNetUsers",
                                principalColumn: "Id",
                                onDelete: ReferentialAction.Cascade);
                        });
        
                    migrationBuilder.CreateTable(
                        name: "AspNetUserLogins",
                        columns: table => new
                        {
                            LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
                            ProviderKey = table.Column<string>(maxLength: 128, nullable: false),
                            UserId = table.Column<string>(maxLength: 128, nullable: false)
                        },
                        constraints: table =>
                        {
                            table.PrimaryKey("PK_dbo.AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey, x.UserId });
                            table.ForeignKey(
                                name: "FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId",
                                column: x => x.UserId,
                                principalTable: "AspNetUsers",
                                principalColumn: "Id",
                                onDelete: ReferentialAction.Cascade);
                        });
        
                    migrationBuilder.CreateTable(
                        name: "AspNetUserRoles",
                        columns: table => new
                        {
                            UserId = table.Column<string>(maxLength: 128, nullable: false),
                            RoleId = table.Column<string>(maxLength: 128, nullable: false)
                        },
                        constraints: table =>
                        {
                            table.PrimaryKey("PK_dbo.AspNetUserRoles", x => new { x.UserId, x.RoleId });
                            table.ForeignKey(
                                name: "FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId",
                                column: x => x.RoleId,
                                principalTable: "AspNetRoles",
                                principalColumn: "Id",
                                onDelete: ReferentialAction.Cascade);
                            table.ForeignKey(
                                name: "FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId",
                                column: x => x.UserId,
                                principalTable: "AspNetUsers",
                                principalColumn: "Id",
                                onDelete: ReferentialAction.Cascade);
                        });
        
                    migrationBuilder.CreateIndex(
                        name: "RoleNameIndex",
                        table: "AspNetRoles",
                        column: "Name",
                        unique: true);
        
                    migrationBuilder.CreateIndex(
                        name: "IX_UserId",
                        table: "AspNetUserClaims",
                        column: "UserId");
        
                    migrationBuilder.CreateIndex(
                        name: "IX_UserId",
                        table: "AspNetUserLogins",
                        column: "UserId");
        
                    migrationBuilder.CreateIndex(
                        name: "IX_RoleId",
                        table: "AspNetUserRoles",
                        column: "RoleId");
        
                    migrationBuilder.CreateIndex(
                        name: "IX_UserId",
                        table: "AspNetUserRoles",
                        column: "UserId");
        
                    migrationBuilder.CreateIndex(
                        name: "UserNameIndex",
                        table: "AspNetUsers",
                        column: "UserName",
                        unique: true);
                }
        
                protected override void Down(MigrationBuilder migrationBuilder)
                {
                    migrationBuilder.DropTable(
                        name: "__MigrationHistory");
        
                    migrationBuilder.DropTable(
                        name: "AspNetUserClaims");
        
                    migrationBuilder.DropTable(
                        name: "AspNetUserLogins");
        
                    migrationBuilder.DropTable(
                        name: "AspNetUserRoles");
        
                    migrationBuilder.DropTable(
                        name: "Dietary");
        
                    migrationBuilder.DropTable(
                        name: "Locations");
        
                    migrationBuilder.DropTable(
                        name: "TbTrainingForm");
        
                    migrationBuilder.DropTable(
                        name: "AspNetRoles");
        
                    migrationBuilder.DropTable(
                        name: "AspNetUsers");
                }
            }
        }
    
    // Controller
    public ActionResult SaveRegForm()
            {
                ViewBag.Message = "Details saved successfull";
                return View(db.TrainingRegs.ToList()); // Error is thrown here.
            }
    
       //GET:TrainingRegForm/Submit.
           public ActionResult SubmitRegDetails()
            {
                // Initialization.
                this.ViewBag.CountryList = this.GetCountryList();
                this.ViewBag.SaveRegForm = this.SaveRegForm();
    
                RegViewAndRoleViewModel model = new RegViewAndRoleViewModel();
    
                return View(model);
            }
    
    // Model
      public partial class TbTrainingForm
        {
            [Key]
            public Guid? Id { get; set; }
            public string Title { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Position { get; set; }
            public string Company { get; set; }
            
            public string StreetAddress { get; set; }
    
           
            public string StreetAddressLine { get; set; }
    
            
            public string City { get; set; }
    
            public string StateProvince { get; set; }
    
            
            public int ZipCode { get; set; }
    
            public string Country { get; set; }
    
           
            public string Email { get; set; }
    
            
            public int CellNumber { get; set; }
            public string DietaryRequirement { get; set; }
        }

using System.Data.Entity;
using eNtsaRegistrationTraining.Models;

namespace eNtsaRegistrationTraining.DAL
{
    public class eNtsaRegistration:DbContext
    {

        public eNtsaRegistration() : base("eNtsaRegistration")
        {
        }  public DbSet<TrainingRegForm> TrainingRegs { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
 }

// View
@model eNtsaRegistrationTraining.Models.RegViewAndRoleViewModel

@using (Html.BeginForm("SaveRegForm", "Home", FormMethod.Post))
                    {


                        <div class="form-horizontal">

                            <hr />

                            <div class="form-group row">
                                <label for="Title" class="col-sm-2 col-form-label">Title</label>
                                <div class="col-sm-3 ">
                                    @Html.EditorFor(model => model.RegForm.Title, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.RegForm.Title, "", new { @class = "text-danger" })

                                </div>
                            </div>

                            <div class="form-group row">
                                <label for="Name" class="col-sm-2 col-form-label">Name:</label>
                                <div class="col-sm-3 ">
                                    @Html.EditorFor(model => model.RegForm.FirstName, new { htmlAttributes = new { @class = "form-control", autofocus = "autofocus", placeholder = "Name" } })
                                    @Html.ValidationMessageFor(model => model.RegForm.FirstName, "", new { @class = "text-danger" })

                                </div>

}

1 Ответ

0 голосов
/ 13 июля 2020

Большая часть ваших файлов .cs, связанных с Entity Framework, - это сгенерированные классы ( представления сопоставления ), которые должны соответствовать вашей базе данных и определениям таблиц.

Когда представления сопоставления не соответствуют вашим последние изменения в базе данных или (измененный, перенесенный) DbContext, вы получите это сообщение об ошибке.

Вы установили расширение EF power tools? Вы можете найти его в Интернете в меню расширений Visual Studio.

https://marketplace.visualstudio.com/items?itemName=ErikEJ.EntityFramework6PowerToolsCommunityEdition

.. когда вы устанавливаете его, щелкните правой кнопкой мыши для создания нового сопоставления просматривать файлы для вашего DbContext.

https://www.c-sharpcorner.com/UploadFile/ff2f08/pre-generated-views-with-a-code-first-model-entity-framework/

...