c# - UnintentionalCodeFirstException | Entity Framework Unit Testing with Effort.Ef6 using Database First -
the situation
i want enable unit testing of dbcontext
based on entity framework 6. have created dbcontext
, models database first approach , have .edmx designer file.
the problem
my automatically created dbcontext
override dbcontext.onmodelcreating
method this:
protected override void onmodelcreating(dbmodelbuilder modelbuilder) { throw new unintentionalcodefirstexception(); }
i trying create new instance of dbcontext
in mocked data access service based on information of this article. code doesn't run database.setinitializer;
author of blog post pointed out. constructor looks his. dbcontext
initialization looks this:
public databaseentities(dbconnection connection) : base(connection, true) { }
which results in following exception when reaching mentioned overridden onmodelcreating
system.data.entity.infrastructure.unintentionalcodefirstexception: 'the context being used in code first mode code generated edmx file either database first or model first development. not work correctly. fix problem not remove line of code throws exception. if wish use database first or model first, make sure entity framework connection string included in app.config or web.config of start-up project. if creating own dbconnection, make sure entityconnection , not other type of dbconnection, , pass 1 of base dbcontext constructors take dbconnection. learn more code first, database first, , model first see entity framework documentation here: http://go.microsoft.com/fwlink/?linkid=394715'
there plenty of questions on stackoverflow focus on unit testing effort while using database-first apporach, no 1 seems have similar problems me.
what have tried do
- searching internet long time solution.
- uncomment overridden
onmodelcreating()
. - i have tried apply this solution without success.
- mock
dbcontext
moq, not option.
the question
how can create , use in-memory database (with effort)?
additional information
when uncomment onmodelcreating()
, exception thrown @ first access datacontext. e.g.:
dbconnection effortconnection = effort.dbconnectionfactory.createpersistent("mockeddatabaseentities"); using (databaseentities datacontext = new databaseentities(effortconnection)) { datacontext.students.count(); // exception throws here }
system.data.entity.modelconfiguration.modelvalidationexception: 'one or more validation errors detected during model generation: myapplication.shared.model.keyvaluepair: : entitytype 'keyvaluepair' has no key defined. define key entitytype. keyvaluepairs: entitytype: entityset 'keyvaluepairs' based on type 'keyvaluepair' has no keys defined.'
the problem had specify key keyvaluepair dataset.
protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<keyvaluepair>().haskey(x => x.key); base.onmodelcreating(modelbuilder, null); }
thank robert jørgensgaard engdahl !
Comments
Post a Comment