c# - ApplicationDbContext Seed starts only if I go to Person Controllers index action in ASP .NET MVC 5.1 application -
i run web application homecontroller.index()
action run. go person.index()
(it @ bottom of post) via browser , migrations.configuration.seed()
invoked. want happen @ 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 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 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 { // can add profile data user adding more properties applicationuser class, please visit http://go.microsoft.com/fwlink/?linkid=317594 learn more. public class applicationuser : identityuser { public async task<claimsidentity> generateuseridentityasync(usermanager<applicationuser> manager) { // note authenticationtype must match 1 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"?> <!-- more information on how configure 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" /> <!-- 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 // protect overposting attacks, please enable specific properties want bind to, // 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 // protect overposting attacks, please enable specific properties want bind to, // 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 }); } } }
database.setinitializer
runs whenever there activity within context. going personcontroller set off setinitializer
have in application start.
add new applicationdbcontext ().database.initialize(true);
in replacement of initializer.
Comments
Post a Comment