问题
I have a website and a windows service that both reference the same project to get an Entity Framework data context. Each time I start the windows service, Entity Framework runs an automatic migration that changes one of the database columns from NOT NULL to NULL (no other changes are made). The property for that column is marked as [Required], and the website (which points to the exact same version of the exact same DLL for its model), properly thinks that the database should be NOT NULL for that column.
I tried disabling automatic migrations and, as expected, the service then crashed because it said that the data model had pending changes that needed to be applied.
Edit I've found out a bit more info... it seems that this is happening because I have both [Required] and [AllowHtml] attributes on the property. When I removed the [AllowHtml] attribute, it didn't happen. So, my question comes down to: 1) is it expected behavior that [AllowHtml] would not work with [Required], and 2) how is it possible that this would only happen when the web service uses this code, and not when the website uses the code? It seems that the web service completely ignores [Required] when it sees [AllowHtml].
I'm using EF 5.
回答1:
I had the exact problems... For the pending changes I had to add three lines into my global.asax file on startup, this is what it looks like:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
AuthConfig.RegisterOpenAuth();
Database.SetInitializer<EntityContext>(null);
EntityContext context = new EntityContext();
context.Database.Initialize(true);
}
As for the [Allowhtml], are you using mvc? ...as far as I can tell [AllowHtml] belongs to the System.Web.Mvc namespace: http://msdn.microsoft.com/en-us/library/system.web.mvc.allowhtmlattribute(v=vs.98).aspx . AllowHtml is intended to use only for Model binding of a type. They are not intended for Form, QueryString or FormCollection model binding. http://forums.asp.net/t/1645209.aspx If a property is marked with the AllowHtmlAttribute attribute, the ASP.NET MVC framework skips validation for that property during model binding, thus rignores your [Required] attribute...
The reason that the column is changing from NOT NULL to NULL is because the [Required] attribute overrides the database schema rule that allows a data field to be empty. http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.aspx
Hope this helps...
回答2:
In the EF project, have you tried disabling automatic migrations, and then forcing EF to not keep the model and db in sync?
In your global.asax file, add:
Database.SetInitializer<dbContext>(null);
This will remove the message that pending migrations need to be applied
Cheers, Bartek
来源:https://stackoverflow.com/questions/18601498/entity-framework-code-first-migrations-thinks-there-is-a-change-that-shouldnt-b