별도의 어셈블리에서 컨텍스트로 마이그레이션을 사용 하시겠습니까?
실행하려는 프로젝트가 하나 update-database
있지만 별도의 프로젝트에 모델과 컨텍스트가 있습니다.
실행 enable-migrations
하면 다음 오류가 발생합니다. 'MyProject'어셈블리에서 컨텍스트 유형을 찾을 수 없습니다.
이것은 아마도 내 컨텍스트가 MyProject.MVC에 있기 때문일 것입니다.
enable-migrations
MyProject.MVC에 대해 실행 하는 경우 앱 구성 파일을 추가해야합니다. 많은 프로젝트에서 코드를 사용하고 싶기 때문에 그렇게하고 싶지 않습니다.
그래서 enable-migrations
MyProject에 대해 실행 하고 어떻게 든 MyProject.MVC에서 컨텍스트를 찾도록 말할 수 있습니까?
이것은 EF 6에서만 작동하지만 명령에 매개 변수를 추가 한 릴리스 가 있습니다. 이 명령을 사용하여 다음을 수행 할 수 있습니다.-ContextProjectName
-enable-migrations
enable-migrations -ContextProjectName MyProject.MVC -StartUpProjectName MyProject.MVC
-ContextTypeName MyProject.MVC.MyContextFolder.MyContextName -ProjectName MyProject
.NET Framework MyProject
의 컨텍스트를 사용 하여 프로젝트 에 마이그레이션을 추가 합니다 MyProject.MVC
. 마이그레이션이있는 프로젝트에 컨텍스트가있는 프로젝트에 MyProject
대한 참조 ( 예 : 참조)가 있는지 확인해야합니다.MyProject.MVC
Database Context 클래스를 포함하는 프로젝트에서만 "Enable-Migrations"를 실행할 수 있습니다.
솔루션에는 2 개의 프로젝트가 포함됩니다.
1) MyProject.Models
|- Migrations
|- 201401061557314_InitialCreate.cs
|- Configuration.cs
|- MyContext.cs
|- App.config (no connection string)
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
2) MyProject.MVC
|- Filters
|- InitializeSimpleMembershipAttribute.cs
InitializeSimpleMembershipAttribute.cs
namespace MyProject.MVC.Filters
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
try
{
Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext, MyProject.Model.Migrations.Configuration>());
using (var context = new MyContext())
{
context.Database.Initialize(force: true);
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
}
MyProject.MVC를 시작 프로젝트로 설정
패키지 관리자에서 프로젝트 선택 : MyProject.Models
그런 다음 "Enable-Migrations"를 실행하여 MyProject.Models에 "Migrations"폴더를 만듭니다.
"Update-Database"-> 마이그레이션은 시작 프로젝트에서 Web.config의 연결 문자열을 사용하여 마이그레이션을 수행합니다.
해결 방법은 다음과 같습니다.
Add a class into MyProject(the project for migrations). Make this class inherit the dbcontext(the one in MyProject.MVC).
Then run EF migration commands on MyProject.
I had the same problem, and I'm using EntityFramework 4.3.1. It seems that EF6 solves this issue (according to the answer by @SOfanatic) but I didn't want to upgrade to EF6 because of some breaking changes (in the DataAnnotations, for example).
So, what I did to solve this (and what I learned in the process):
Create a new solution (empty project) and add the project where you have the model you want to enable migrations for (in your case MyProject.MVC). You may need to install the required NuGet packages for it before you are able to add the existing project.
Add a config file with a connection string (don't worry, this is only to trick the migrations engine). Copy your existing database to the model project output folder (should be MVC\bin\Debug in your case). Make sure the connection string in the config file points to that database:
<connectionStrings> <add name="MyDB" providerName="System.Data.SqlServerCe.4.0" connectionString="DataSource=|DataDirectory|\MyDB.sdf"/> </connectionStrings>
Since you are in a new solution, set your model project as a startup project (you can remove the default project).
Run the enable-migrations command in the package manager console. It should create a Migrations folder with two files: a Configuration.cs and a timestamped InitialCreate.cs file. It's nice to have the InitialCreate, that's why you put your existing database in the model project's output folder (but this is optional).
Reload your original solution so that these changes are updated.
What I learned (as far as I understand):
- The migrations engine needs something that looks like a valid connection to work. I was creating my connection string in code (in another project) and that didn't work. I just gave the Migrations engine a "valid" connection string to make it work.
- Put your database where the migrations engine can find it (aka model project's output folder) so it creates a starting point for migrations. This starting point is basically your database schema written in the migrations API.
- You can restore everything to your previous state once the migrations are set in place, and it works ok.
- Everytime you want to manually add a migration, you must "trick" the migrations engine again, just like the first time. I haven't tried with automatic migrations, by I guess this approach works as well.
By th way, I am using a SQL Server CE 4.0 database, so some things about the connection string have a little twist compared to a standard SQL Server DB or LocalDB. Besides that, everything's the same.
Hope this is helpful and gives you some insight. Please comment if you know more about the way this migrations work.
참고URL : https://stackoverflow.com/questions/18126711/enable-migrations-with-context-in-separate-assembly
'IT TIP' 카테고리의 다른 글
자바 스크립트에서 nl2br () 해당 (0) | 2020.11.21 |
---|---|
제한 및 주문과 결합 된 ActiveRecord find_each (0) | 2020.11.21 |
CSS로 직사각형 이미지를 원형으로 만드는 방법 (0) | 2020.11.21 |
텍스트가 허용 된 것보다 큰 경우 CSS로 오버플로시 텍스트 페이드 아웃 (0) | 2020.11.21 |
S3 객체에 데이터 추가 (0) | 2020.11.21 |