4
votes

so far i was creating a classLibrary project and inserting new Ado.net Entity data model and genareting from exixting database. Class and object class codes are creating automatically. this is not important for me.

but i want to do this and separate the ObjectContext class (ex: SomeEntities) and table classess to two calss library.

when i change the database tables property, i will update edmx model and classes will update automatically.

is there any way to do this? i am not using codefirst because have a database and datas in it, i am not using modelfirst likewise, i am using databasefirst but can not separate

1
You can still use CodeFirst with an existing database.taylonr
@taylonr - that is not code-first that is using DbContext API with database-first. Code-first = write a code and let EF generated DB. Code-first != DbContext API, it is only subset of DbContext API as well as Code-first != fluent mapping because you can use fluent mapping to existing db which mean that the database was created first, not the code.Ladislav Mrnka
While your comment is true, it also indicates the methods that people are using. A lot of the time when people say they're doing code first they mean they're doing using the DB context and POCOs. Especially in this case, the user is talking about how he's doing DB first so he has an edmx. I should have been more clear and said he could do POCOs in a code-first style and not overwrite his db.taylonr

1 Answers

8
votes

Since you have "poco" in your title I guess that you are using the EF4 POCO Generator T4 Template.

Then yes, you can separate POCO classes and ObjectContext into two different class libraries. The T4 Template is prepared for that scenario since it consists of two different files:

  • POCOGenerator.Context.tt -> responsible to create your derived ObjectContext
  • POCOGenerator.tt -> responsible to create your POCO entities

If you add the POCO generator in the class library where you have your EDMX file, by default both tt-files will be added there.

But you can move then the second file (POCOGenerator.tt) into another class library. (The EDMX project where the context is located needs to reference this library to recognize the POCO classes.) After that open this file in a text editor. Some of the first lines in this file will look like:

...
string inputFile = @"MyModel.edmx";
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
...

You now need to change the path to the edmx file (only in POCOGenerator.tt, leave POCOGenerator.Context.tt unchanged). Assuming you have edmx project and POCO project in the same solution of Visual Studio, the new path might be:

...
string inputFile = @"..\..\MyEDMXProject\MyModel.edmx";
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
...

Now you can execute both files separately from two different projects. One will create the context file and the other will create your POCO files.