asp.net mvc - Issue in Connecting Web App with localdb using DataContext file and webConfig file -
i have created mvc web application using repository & di approach. have used code first approach too.
here datacontext file:
namespace efreppattest.data { public class datacontext : dbcontext, idbcontext { public new idbset<tentity> set<tentity>() tentity: class { return base.set<tentity>(); } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { var typestoregister = assembly.getexecutingassembly().gettypes() .where(type => !string.isnullorempty(type.namespace)) .where(type => type.basetype != null && type.basetype.isgenerictype && type.basetype.getgenerictypedefinition() == typeof(entitytypeconfiguration<>)); foreach (var type in typestoregister) { dynamic configurationinstance = activator.createinstance(type); modelbuilder.configurations.add(configurationinstance); } base.onmodelcreating(modelbuilder); } } }
i have defined connecting string in web.config file below:
<add name="datacontext" connectionstring="data source=(localdb)\v11.0;attachdbfilename=|datadirectory|\ecommerce.mdf;integrated security=true" providername="system.data.sqlclient" />
please note here have mentioned same name connection string , context file.
here post method:
[httppost] public actionresult create(categorymodel model)//formcollection collection { try { // todo: add insert logic here if (model == null) return view(model); var category = new category(); category.name = model.name; categoryservice.insert(category); return redirecttoaction("index"); } catch { return view(model); } }
categoryservice:
public class categoryservice : icategoryservice { private irepository<category> _categoryrepository; public categoryservice(irepository<category> categoryrepository) { this._categoryrepository = categoryrepository; } public void insert(category category) { if (category == null) throw new argumentnullexception("category"); _categoryrepository.insert(category); } }
repositoryservice:
public class repositoryservice<tentity> : irepository<tentity> tentity: class { private idbcontext _context; private idbset<tentity> entities { { return this._context.set<tentity>(); } } public repositoryservice(idbcontext context) { this._context = context; } public void insert(tentity entity) { entities.add(entity); } }
when run application on first time create local db. when going insert data, did not error application , not insert data db.
what cause this? have done wrong here?
any appreciated!
you should call savechanges()
on _context
after changes ex.:
public void insert(tentity entity) { entities.add(entity); _context.savechanges(); }
Comments
Post a Comment