[.net] 데이터베이스가 작성된 이후 <Database> 컨텍스트를 지원하는 모델이 변경되었습니다.

오류 메시지 :

” ‘주소록’컨텍스트를 뒷받침하는 모델은 데이터베이스가 작성된 후 변경되었습니다. 데이터베이스를 수동으로 삭제 / 업데이트하거나 IDatabaseInitializer 인스턴스를 사용하여 Database.SetInitializer를 호출하십시오. 예를 들어 RecreateDatabaseIfModelChanges 전략은 데이터베이스를 자동으로 삭제하고 다시 작성합니다. 선택적으로 새로운 데이터로 시딩합니다. “

코드 우선 기능을 사용하려고하는데 다음과 같이 작성했습니다.

var modelBuilder = new ModelBuilder();
var model = modelBuilder.CreateModel();
using (AddressBook context = new AddressBook(model))
{
    var contact = new Contact
    {
        ContactID = 10000,
        FirstName = "Brian",
        LastName = "Lara",
        ModifiedDate = DateTime.Now,
        AddDate = DateTime.Now,
        Title = "Mr."

    };
    context.contacts.Add(contact);
    int result = context.SaveChanges();
    Console.WriteLine("Result :- "+ result.ToString());
}

컨텍스트 클래스 :

public class AddressBook : DbContext
{
    public AddressBook()
    { }
    public AddressBook(DbModel AddressBook)
        : base(AddressBook)
    {

    }
    public DbSet<Contact> contacts { get; set; }
    public DbSet<Address> Addresses { get; set; }
}

연결 문자열 :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
    <add name="AddressBook" providerName="System.Data.SqlClient"
         connectionString="Data Source=MyMachine;Initial Catalog=AddressBook;
         Integrated Security=True;MultipleActiveResultSets=True;"/>
    </connectionStrings>
</configuration>

따라서 데이터베이스 이름은 “AddressBook”이며 연락처 개체를 컨텍스트에 추가하려고하면 오류가 발생합니다. 여기에 빠진 것이 있습니까?



답변

이제는 :

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer<YourDbContext>(null);
    base.OnModelCreating(modelBuilder);
}

YourDbContext.cs 파일에


답변

다음 은 Jeff가 게시 한 Scott Gu 블로그 의 실제 정보입니다.

이 예외가 발생하는 경우 :

“데이터베이스가 생성 된 이후 ‘생산’컨텍스트를 백업 모델이 변경되었습니다. 수동 / 삭제 데이터베이스, 또는 전화 업데이트 Database.SetInitializerIDatabaseInitializer인스턴스를.”

다음은 진행중인 작업과 수행 할 작업입니다.

모델이 처음 생성되면 DatabaseInitializer를 실행하여 데이터베이스가 없거나 시드 데이터를 추가하는 경우 데이터베이스 생성과 같은 작업을 수행합니다. 기본 DatabaseInitializer는 모델을 사용하는 데 필요한 데이터베이스 스키마와 데이터베이스로 작성된 EdmMetadata 테이블에 저장된 스키마의 해시 (코드 우선이 데이터베이스를 작성하는 경우)를 비교하려고합니다. 기존 데이터베이스에는 EdmMetadata 테이블이 없으므로 해시가 없습니다. 해당 테이블이 누락되면 오늘 구현에서 예외가 발생합니다. 우리는이 버전이 기본 버전이기 때문에이 버전을 변경하기 위해 노력할 것입니다. 그때까지 기존 데이터베이스에는 일반적으로 데이터베이스 초기화 프로그램이 필요하지 않으므로 다음을 호출하여 컨텍스트 유형에 대해 해제 할 수 있습니다.

Database.SetInitializer<YourDbContext>(null);

제프


답변

들어 6.1.3 – 엔티티 프레임 워크 5.0.0.0

당신은 DO 실제로 다음을 수행 할 :

1. using System.Data.Entity;   to startup file (console app --> Program.cs / mvc --> global.asax
2. Database.SetInitializer<YourDatabaseContext>(null);

예, 매트 Frear가 맞습니다. 업데이트-편집 : 주의 사항은이 코드를 global.asax에 DbContext 클래스에 추가하는 대신 다른 사람들과 동의한다는 것입니다.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // other code 
    Database.SetInitializer<YOURContext>(null);
    // more code here.
}

다른 사람들이 언급했듯이 이것은 단위 테스트를 처리하는데도 좋습니다.

현재 Entity Framework 6.1.3 /.net 4.6.1에서 이것을 사용하고 있습니다.

가까운 시일 내에 CORE 스 니펫을 제공하기 위해 다시 방문 할 것입니다.


답변

SQL Server Management Studio에서 followng sql 명령을 실행하십시오.

delete FROM [dbo].[__MigrationHistory]


답변

이 수정은 CTP5 이후에는 더 이상 작동하지 않습니다.

너가해야되는 Database.SetInitializer<YourContext>(null);


답변

여기에 대한 답변과 업데이트를 생각했습니다. 다음을 수행하면됩니다.

public class AddressBook: DbContext
{
   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
    modelBuilder.IncludeMetadataInDatabase = false;
   }
}


답변

또는 Application_Start () 아래의 Global.asax.cs 파일에이 줄을 넣을 수 있습니다.

System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<ProjectName.Path.Context>());

ProjectName.Path.Context를 네임 스페이스 및 컨텍스트로 변경하십시오. 코드를 먼저 사용하면 스키마가 변경 될 때마다 새 데이터베이스가 삭제되고 작성됩니다.