问题
I run the Web Application HomeController.Index()
action is run. Then I go to Person.Index()
(it is at the bottom of this post) via browser then and only then Migrations.Configuration.Seed()
is invoked. But I want it to happen at the application start.
Configuration:
namespace WebApplication2.Migrations {
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using WebApplication2.Models;
internal sealed class Configuration : DbMigrationsConfiguration<WebApplication2.Models.ApplicationDbContext> {
public Configuration() {
AutomaticMigrationsEnabled = true;
ContextKey = "WebApplication2.Models.ApplicationDbContext";
}
protected override void Seed(WebApplication2.Models.ApplicationDbContext context) {
System.Diagnostics.Debug.WriteLine("Seed started");
// System.Data.Entity.DropCreateDatabaseAlways<ApplicationDbContext> s = new DropCreateDatabaseAlways<ApplicationDbContext>();
// s.InitializeDatabase(context);
if (!context.Persons.Any()) {
var persons = new List<Person> {
new Person{FirstName = "John", LastName = "Doe", CellNumber = "123-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "312312312", Notes = "Annoying"},
new Person{FirstName = "Anna", LastName = "Doe", CellNumber = "113-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "548555672", Notes = "Less Annoying"}
};
persons.ForEach(person => context.Persons.AddOrUpdate(person));
context.SaveChanges();
}
if (!context.Meetings.Any()) {
var meetings = new List<Meeting>{
new Meeting{PersonId = 1, Body = "Body of meeting", Date = DateTime.Now}
};
meetings.ForEach(meeting => context.Meetings.AddOrUpdate(meeting));
context.SaveChanges();
}
if (!context.Statuses.Any()) {
var statuses = new List<Status> {
new Status{Name = "OK"},
new Status {Name = "NOT_OK"}
};
statuses.ForEach(status => context.Statuses.AddOrUpdate(status));
context.SaveChanges();
}
//Users Seeding
if (!context.Users.Any()) {
System.Diagnostics.Debug.WriteLine("USER SEED");
try {
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
//why user is not created
var user1 = new ApplicationUser { UserName = "admin", Email = "informatyka4444@wp.pl" };
var user2 = new ApplicationUser { UserName = "emp", Email = "informatyka4444@wp.pl" };
manager.Create(user1, "admin");
manager.Create(user2, "emp");
context.SaveChanges();
} catch (Exception e) { System.Diagnostics.Debug.WriteLine("THERE WAS AN EXCEPTION"); }
}
}
}
}
IdentityModels.cs
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace WebApplication2.Models {
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser {
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false) {
System.Diagnostics.Debug.WriteLine("CONSTRCTOR");
// Database.SetInitializer(new DropCreateDatabaseAlways<ApplicationDbContext>());
}
public DbSet<Person> Persons { get; set; }
public DbSet<Meeting> Meetings { get; set; }
public DbSet<Status> Statuses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public static ApplicationDbContext Create() {
return new ApplicationDbContext();
}
}
}
Global.asax:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApplication2.Migrations;
using WebApplication2.Models;
namespace WebApplication2 {
public class MvcApplication : System.Web.HttpApplication {
protected void Application_Start() {
System.Diagnostics.Debug.WriteLine("Application_Start");
Database.SetInitializer(new DropCreateDatabaseAlways<ApplicationDbContext>());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
Web.Config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication2-20140711041006.mdf;Initial Catalog=aspnet-WebApplication2-20140711041006;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<!-- <contexts>
<context type="WebApplication2.Models.ApplicationDbContext, WebApplication2">
<databaseInitializer type="WebApplication2.Migrations.Configuration, WebApplication2" />
</context>
</contexts>-->
<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>
The Person
controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Models;
namespace WebApplication2.Controllers {
public class PersonController : Controller {
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Person
public ActionResult Index() {
return View(db.Persons.ToList());
}
// GET: Person/Details/5
public ActionResult Details(int? id) {
if (id == null) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = db.Persons.Find(id);
if (person == null) {
return HttpNotFound();
}
return View(person);
}
// GET: Person/Create
public ActionResult Create() {
return View();
}
// POST: Person/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,FirstName,LastName,CellNumber,SecondaryPhoneNumber,Address,BirthDate,Pesel,Notes")] Person person) {
if (ModelState.IsValid) {
db.Persons.Add(person);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
// GET: Person/Edit/5
public ActionResult Edit(int? id) {
if (id == null) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = db.Persons.Find(id);
if (person == null) {
return HttpNotFound();
}
//Moj kod
//Album album = db.Albums.Find(id);
//ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
//ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
ViewBag.StatusId = new SelectList(db.Statuses, "Id", "Name", person.StatusId);
//Moj kod
return View(person);
}
// POST: Person/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,CellNumber,SecondaryPhoneNumber,Address,BirthDate,Pesel,Notes,StatusId")] Person person) {
if (ModelState.IsValid) {
db.Entry(person).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
// GET: Person/Delete/5
public ActionResult Delete(int? id) {
if (id == null) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = db.Persons.Find(id);
if (person == null) {
return HttpNotFound();
}
return View(person);
}
// POST: Person/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id) {
Person person = db.Persons.Find(id);
db.Persons.Remove(person);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing) {
if (disposing) {
db.Dispose();
}
base.Dispose(disposing);
}
public string formatPhoneNumber(string number) {
Regex rgx = new Regex("[^0-9]");
return rgx.Replace(number, "");
}
public ActionResult Call(int id, string number) {
System.Diagnostics.Process proc = new System.Diagnostics.Process();
string formattedNumber = "tel:+48" + formatPhoneNumber(number);
System.Diagnostics.Debug.WriteLine("NUMBER " + formattedNumber);
proc.StartInfo.FileName = formattedNumber;
proc.Start();
Person person = db.Persons.Find(id);
return RedirectToAction("Edit", new Person { Id = id });
}
}
}
回答1:
Database.SetInitializer
runs whenever there is activity within your context. You going to your PersonController would set off the SetInitializer
you have in your Application Start.
Add new ApplicationDbContext ().Database.Initialize(true);
In replacement of your Initializer.
来源:https://stackoverflow.com/questions/25354718/applicationdbcontext-seed-starts-only-if-i-go-to-person-controllers-index-action