How to implement DbContext hierarchy - entity-framework

What I'd LIKE to do is manipulate EF to support plugins that access a shared database. So the database would contain all of the tables for the main application plus all of the tables required for each plugin. As the application doesn't know anything about the plugin data structures, it cannot be responsible for their management. The plugins are solely responsible, and create the tables themselves. However, the plugins know about the host application and its data structures, so ideally should be able to reference them and even inherit from them, resulting in a database that is extensible yet able to implement optimized patterns.
In EF, this translates to a HostContext that contains the DbSets appropriate for the Host. Each Plugin, I thought, should have a PluginContext that inherits from HostContext that contains the DbSets needed by the plugin. The entity classes included in PluginContext would then be able to reference HostContext entities, and/or inherit from those entities, and EF would be able to resolve the table mapping and relationships.
I'm using EF6. When I attempt the above and try to list the single entity I've included in the PluginContext, an exception is thrown complaining that the entity doesn't exist. Sure enough, no matching table has been created.
Is what I'm attempting to do supported by EF? If so, what am I doing wrong?

As I mentioned here: EF6 Empty Model target string
I began this effort using Rowan Miller's example here: http://romiller.com/2013/02/15/extending-and-customizing-code-first-models-part-2-of-2/
In the end, I abandoned that approach, for a few reasons: 1) I couldn't get it to work (I can't remember exactly why but I do suspect it was related to differences in EF since the article was written), and 2) I didn't like the need to write manual migrations.
I ended up with PluginContexts that inherit from HostContext, as I had hoped, and am able to reference and even inherit from host entities. This has restrictions in its use though:
My plugin logic is completely self contained. I have no need for the host application to manipulate or create plugin entities. Therefore, I am not trying to get the system to subsitute any plugin entities for host entities. If construction of a particular entity subclass is required, then a plugin method must be provided for that and an inheritence hiearchy will be utilized.
Migrations can be built even on the plugin context as per normal. However, that migration may easily include migration code from the Host Context. So I have to remember to look for and remove these instructions. This is typically very straightforward and I believe is much less effort than building the equivalent from scratch.
If there is any change to the Host Context then this must be reflected in every Plugin Context. Basically, this means anytime a new migration is created to reflect changes in Host Context, migrations must be created for each plugin as well, even though that migration may be empty (it isn't really - the critical part here is updating the Model in the latest MigrationHistory record to reflect the Plugin model that has been changed because of the inherited Host model).
This approach is being used to extend an in-house application with in-house plugins, and so may not be as easy to adopt in other scenarios which Rowan's solution is probably better suited.

Related

Getting familiar with Entity Framework when using existing database

We are currently rewriting an existing internal ASP.NET Web Forms application. Our application consists of a Web Api back end which uses Entity Framework 6 for data access and an front end which uses AngularJS.
We have an existing large database that I've created EF models using the Code-First Using Existing Database method and we are using data transfer object classes as inputs/outputs to our API methods so we aren't directly exposing our model classes. So basically, I'm trying to become proficient with EF, Web Api and AngularJS all at the same time. For the most part I'm fairly comfortable with the latter two, but for EF I haven't completely gotten comfortable with. I've watched a lot of the videos on Microsoft Virtual Academy but this is the first time I've had some hands-on experience with it.
We've been working on this application for a few months and so far we've only had to work with CRUD operations on our entities (POCO DTO's) which are flat objects with simple properties. However, we've finally come across some situations where we need to deal not only with our classes, but properties which are classes themselves; a parent-child relationship.
Therefore, I have the following questions:
I see that when we have a proper foreign key relationship in our DB, that virtual properties are created in EF, which from what I recall are to support lazy-loading. However, lazy-loading isn't really feasible in this environment where we are using web services (Web Api). Our object model does allow for some really large hierarchy of classes where a fully populated object and its children would mean a large amount of data would be passed around when that really isn't necessary, so in most cases a first level object is all we need. In some cases however, we do want to populate child classes, so my question is how do we do that, and where do we do that? I've looked at the automatically-generated code in the DB Context but we have also used scaffolded code to create our controllers. Which place do we need to do this? I've seen code samples showing how do to this but it hasn't said specifically where this code lies. It appears to be within a controller but I could be wrong.
If we do allow for 2- or more level hierarchy of objects, does EF automatically handle operations (updates, deletes, etc.) -- for example, if we have a "Company" object which has a collection of "Customer" objects, and we delete the "Company" object, do the related "Customer" objects get deleted too? Also, is a multi-step operation like that automatically performed within a transaction or do we need to explicitly set that up?
If I modify a model class or the DB context, seeing as this code is automatically-generated, that's generally bad practice as my changes could be overwritten, so I am assuming the controller code is where I want to make my changes. I am aware of database migrations but I have no experience with them and I am sure I'll need to use them at some point because I am fairly confident that our database may not have all the foreign key relationships necessary for EF to do everything we need at the moment.
I know this is a long post, but if anyone can give some guidance on how to do some of these things because it's not only me that's having to deal with this but I have two other developers on my team who are working on this project and we are all as inexperienced with this as the others are. Thanks
For the purpose of sending data across a web service, I'd suggest creating a DTO to hold the data you want to send and mapping your entities to the DTO instead of trying to send the entities themselves in your payload. It also protects your API from changes to your entity.
Cascading deletes are configurable, iirc, but I'm not 100% sure what the default is. Transactions are generally not implicit, so you will want to use those where you require them.
Not exactly sure what you are asking here. In general, how your entities/tables change depends on if you are using database-first or code-first. If you are using database-first (you will have a .edmx file in your solution that has the model matching your schema), you just update the SQL directly and update your entity model via the .edmx. If you use code-first, you will change the entities how you want them and run a database migration to update your database to match.
MSDN article about code-first migration: https://msdn.microsoft.com/en-us/data/jj591621.aspx

Entity Framework 6 Database-First and Onion Architecture

I am using Entity Framework 6 database-first. I am converting the project to implement the onion architecture to move towards better separation of concerns. I have read many articles and watched many videos but having some issues deciding on my solution structure.
I have 4 projects: Core, Infrastructure, Web & Tests.
From what I've learned, the .edmx file should be placed under my "Infrastructure" folder. However, I have also read about using the Repository and Unit of Work patterns to assist with EF decoupling and using Dependency Injection.
With this being said:
Will I have to create Repository Interfaces under CORE for ALL entities in my model? If so, how would one maintain this on a huge database? I have looked into automapper but found issues with it presenting IEnumererables vs. IQueryables but there is an extension available it has to hlep with this. I can try this route deeper but want to hear back first.
As an alternative, should I leave my edmx in Infrastructure and move the .tt T4 files for my entities to CORE? Does this present any tight coupling or a good solution?
Would a generic Repository interface work well with the suggestion you provide? Or maybe EF6 already resolves the Repository and UoW patterns issue?
Thank you for looking at my question and please present any alternative responses as well.
I found a similar post here that was not answered:
EF6 and Onion architecture - database first and without Repository pattern
Database first doesn't completely rule out Onion architecture (aka Ports and Adapters or Hexagonal Architecture, so you if you see references to those they're the same thing), but it's certainly more difficult. Onion Architecture and the separation of concerns it allows fit very nicely with a domain-driven design (I think you mentioned on twitter you'd already seen some of my videos on this subject on Pluralsight).
You should definitely avoid putting the EDMX in the Core or Web projects - Infrastructure is the right location for that. At that point, with database-first, you're going to have EF entities in Infrastructure. You want your business objects/domain entities to live in Core, though. At that point you basically have two options if you want to continue down this path:
1) Switch from database first to code first (perhaps using a tool) so that you can have POCO entities in Core.
2) Map back and forth between your Infrastructure entities and your Core objects, perhaps using something like AutoMapper. Before EF supported POCO entities this was the approach I followed when using it, and I would write repositories that only dealt with Core objects but internally would map to EF-specific entities.
As to your questions about Repositories and Units of Work, there's been a lot written about this already, on SO and elsewhere. You can certainly use a generic repository implementation to allow for easy CRUD access to a large set of entities, and it sounds like that may be a quick way for you to move forward in your scenario. However, my general recommendation is to avoid generic repositories as your go-to means of accessing your business objects, and instead use Aggregates (see DDD or my DDD course w/Julie Lerman on Pluralsight) with one concrete repository per Aggregate Root. You can separate out complex business entities from CRUD operations, too, and only follow the Aggregate approach where it is warranted. The benefit you get from this approach is that you're constraining how the objects are accessed, and getting similar benefits to a Facade over your (large) set of database entities.
Don't feel like you can only have one dbcontext per application. It sounds like you are evolving this design over time, not starting with a green field application. To that end, you could keep your .edmx file and perhaps a generic repository for CRUD purposes, but then create a new code first dbcontext for a specific set of operations that warrant POCO entities, separation of concerns, increased testability, etc. Over time, you can shift the bulk of the essential code to use this, while still keeping the existing dbcontext so you don't lose and current functionality.
I am using entity framework 6.1 in my DDD project. Code first works out very well if you want to do Onion Architecture.
In my project we have completely isolated Repository from the Domain Model. Application Service is what uses repository to load aggregates from and persist aggregates to the database. Hence, there is no repository interfaces in the domain (core).
Second option of using T4 to generate POCO in a separate assembly is a good idea. Please remember that your domain model (core) should be persistence-ignorant.
While generic repository are good for enforcing aggregate-level operations, I prefer using specific repository more, simply because not every Aggregate is going to need all of those generic repository operations.
http://codingcraft.wordpress.com/

Repository and IoC Patterns

Previously I asked this question and on a answer I got this comment:
This works, however injecting the container to a part, as far as I know, is not a "normal" use-case of MEF.
In my web app I have a few repositories that, of course, retrieve entities from the DB. To make them as loosely coupled as possible I'm making them return interfaces (eg IUser, IBill, IBlaBlaBla...) and the repository project only references the library project (that contains the interfaces). I use MEF composition capabilities to tie it all up...
Since the repository must have a concrete object to fill with info it got from the DB and the only the Container is aware of which concrete class maps to a specific interface I think that the repository MUST have reference to the container so it can call the "Resolve()", get a new instance and do his job, but that apparently is a mistake.
Can anyone tell me why and what approach would be better?
PS: I don't know if it's relevant but I'm using DDD...
I think the flaw in your design that lead to this problem is the use of interfaces to hide entities behind. Since entities are your core concept in your domain, there should be no use in hiding them behind an abstraction. Let's put it differently: do you ever have a different implementation of IUser?
In other words, ditch the IUser, IBill, etc. interface and let your repositories and business commands depend directly on your aggregate entities.

EntityFramework - Use Entities in Modules without access to the Database

I'm currently creating an application which is highly modular (using the Prism-Framework) and accesses a database via the EntityFramework implemented in CodeFirst.
My goal is to seperate the actual writing of the data into the Database from the "normal" use of the created Entities. Writing to the Database shall only be done by the main-Application but the Modules should still be able to use the Entity-Classes.
Thus, they must know the DataContext or at least the Entiy Classes. Here is the problem, though: If a module changes a property of an Entity Class and the main-Application calls "SaveChanges()" on the DataContext for some other reason, the changes made by the module are automatically saved to the Database without the main-Application having control over it.
How can I prevent this behaviour? The Modules must not be able to change the Database-Content, except via a defined Interface to the main-Application.
My first thought was to implement ICloneable in every entity-Class and to only pass clones of the Entity-Objects to the Modules to work with. The modules would then, if they wanted to request a change in the database, pass the cloned Objects to the main-Application which updates the original object and calls "SaveChanges()" on the DataContext.
Do you guys think this is a viable solution, or might there be a better way to implement this behaviour?
Thanks in advance!
Use the DbSet.AsNoTracking() Method to enable reading data from the database that will not be tracked by the DbContext.

Is It Possible To Setup An Interface Library For A DAL Using Entity Framework?

I have a model library (namespace Test.App.Model.EF) with the Entity Framework implementation in it. This has all of the entities provided in the EF designer for me which I want to use. Within this Model.EF implementation, I have several repository classes. I want to create interfaces for these classes and place them in a seperate interface library (Test.App.Model.Interface). So I do so, obviously the implementation library needs a reference the interfaces. BUT, I notice that the interfaces need to know about the objects in the EF designer (since I want to reuse them). I can't create a reference from the interface library to the ef implementation because then I'll have a circular reference.
So, as I write this, I'm coming to the conclusion that I'll probably need a Test.App.Entities.EF that has the Entity Framework "created" entities. That way my interfaces lib could reference without having to know about the Model.EF.
Does that sound like the way to go?
Ok, so after much wrestling with this, I found the buzz term that describes the situation. What I'm looking for here is called "Persistence Ignorance". This is what would make what I described in my thread happen. Well the Entity Framework that we use (not 4.0) does not support this yet (unless you go homegrown like done here).
With having that said, EF 4.0 will have this feature but from what I understand, it's coupled with .NET 4.0 (why it's called EF 4.0 in the first place) and that's not going on our production servers anytime soon. Since we've decided to go with this technology, our repository abstraction to interfaces will be placed on hold until upgrading to 4.0 is a viable option.
Let this be a caveat for those seeking the same information. Please also let me know if this sounds incorrect (because I would love to make this happen sooner then later but I don't want my team jumping through hoops when a later implementation will remedy the issue). Thanks all!