Entity framework - Code First - Is it really good approach for big projects? - entity-framework

I have been doing some reading on code first approach of the entity framework and the other approaches(Model first, database first).
1.)The reason supporting entity framework code first approach in a lot of blogs seems to be to keep developers happy so that they dont have to work with designers. I am suprised at this argument because, you develop a project to keep your customers happy and not your developers. How many projects out there have developer happiness in the project plan. Another argument is to avoid a lot of mappings on xml. Well, if not xml, we end up doing that anyways in OnModelCreating and adding [Key] attributes to domain models. So mapping is not eliminated.
2.)Also when you generate a database from the code(domain model), the domain model is designed in an OO way and the generated database structure might not be the optimal one, which forces me to think that this code first approach is only suitable for small projects.
Are arguments correct?

1) The reason for the code first paradigm is to save development time by reducing the amount of tedious repetitive work developers have to do (which in turn makes them happier). Code first allows developers to forget about SQL for the most part (sometimes you will still have to write stored procedures) and focus on the data model and business logic. It is much easier to version your database (especially during development) as each developer only has to change their c# models rather than write a new SQL script, check it in and make sure everyone else on the team knows to run it. As for the XML files in the past in orther ORM's I've found it a pain to constantly lookup the corresponding xml file when you are modifying the domain classes. I personally find the fluent interfaces quicker when making changes to my data model. Also the xml files entity framework used in v1.0 became so large they were a real pain to edit/manage when your database got to be of any real world size.
2) I can't think of a scenario where a data schema could only be created via SQL and not expressed as c# with entity framework code first.

Related

Can’t find best way for apply best in code design techniques in software dev

[Pre]
I have to say that I'm dummy newbie who is trying to get together important puzzles with such crucial details as DDD, TDD, MVVM, and EFCore. I have an about 10 years of windows form develop experience in complete wrong manner, and after I'm joined to Plurasight I'm understood that I'm just lost my last 10 years, and this is really sad :).
[Problem description]
I have an App that i want to re-write from scratch by using latest and greatest technics that've learned for the last 6 month on Pluralsight, but the problem is that these new knowledge’s is stopping me, because simply I'm afraid that I'll do it wrong again...(that is stupid I know, but it is what it is).
So back to my questions, I have a big problem domain, and pretty well documented business logic, which i have to turn in to the code. I'm understand that my start point is design data layer, for these purposes I want to use Entity framework core (I saw Julie Lerman's course on Pluralsight and I think's she is amazing and inspires me to use EFCore as ORM for my app). But at the same time leakage of experience produces more questions than what I’ve learned with Pluralsight, and I will try to write them all(please don’t judge me too hard)
It is looks like that I will need 2 or even more data model projects in my solution, and here is why I have multiple document set types, each of the type contain more than one reference books used to generate unique file names and data sheets. But it looks weird to me have 3 Data model projects such as MyApp.PackType1.DataModel, MyApp.PackType2.DataModel, and each of them will be preinstalled with the EFCore, and each of them will generates its own database based on Data Context defined by EF. Isn’t it very redundant or this is correct way?
I don’t understand how to join these multiple Data Models projects, including Shared Kernel into the one nice model
I don’t understand what is the best way to design my data classes? Should they be just POCO’s or I can design them as nice looking classes with the private var’s and public properties? What are the best practices in here?
Also I don’t understand what is the best practice to use a MVVM pattern on top of that, and is it applicable at all to use MVVM in this case?
Should I keep my Tests in separate projects like MyApp.PackType1.DataModel.Tests, or keep them in same project?
Best regards,
Maks!
P.S.
Apologize for unclear definitions and questions, English isn't my native language.
It's very complicated to answer your question because you have asked for a lot of details, but I going to provide a brief answer and I hope it will be helpful.
You can have only one model for your entities (DDD) and create sub model from this model in your end level projects (Web API or UI)
Read point #1
You have to create an Entity Layer project that represents your database and then you can create DTO's for specific scenarios
From my point of view, use Angular but you can use another UI framework such as React or VueJs, but I prefer to use Angular to build UI interfaces and consume .NET Core Web API from client
Create unit tests and integration tests for you Web API projects and as additional feature you can use Db in memory provider for tests
May be this guide is useful: https://www.codeproject.com/Articles/1160586/Entity-Framework-Core-for-Enterprise
Regards
Hm, multiple DbContexts (models) usually come about when you have distinct databases you are using. General rule is one Context = one Database. Exceptions can occur when there are a lot of tables that can be grouped functionally, but there are downsides to that approach.
A DbContext is a repository pattern but for individual tables. Using a Unit of Work pattern and layering with a custom repository provider would allow you to make it "appear" as a single database, hiding the complexity from the front-end.
Your entity descriptions are usually created as straight POCO. You can get creative with different DTOs
In a nutshell, an MVVM pattern goes like this:
Request from UI to a controller
Controller possibly issues multiple calls to Data Layer to gather data
Assemble data in a single ViewModel (everything the page needs)
Return to UI
The beauty of the approach is single roundtrip (request/response) to the UI
Separate Project in my opinion. There are techniques to spoof the database connection using EF so you are not using "live" data.
That CodeProject article will come in handy.

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/

Is Entity Framework good for bigger Database?

I used Entity framework with a database having around 50 tables and it worked just fine.
But just to see what happens with a larger database in terms of number of tables/entities i tried to implement the Entity Framework to a database that had around 100+ tables.
Once i selected all the tables and clicked on the Finish Button on the Entity Framework Wizard its just hanged my VS 2010 so i could not get any results.
My Questions are as below;
1.If I have larger Database in terms of Table/Entites as described above, Is it a good idea to use Entity Framework?
2.What will be the better approch using Entity Framework to work with database?
3.Should i create multiple DataContext or EDMX files with lesser entites in it?
4.How will these different DataContext interact with each other?
5.Is there any recommended no of tables that should be used while working with Entity Framework?
#Will is correct that the limitation you're seeing is in the designer, but it's not the only one, so Code-First doesn't necessarily fix the problem.
If the designer seems slow, it's inconvenient, but not the end of the world. Runtime performance considerations are another thing altogether. For performance-critical tasks and tuning, you'll want to understand the whole pipeline.
View generation, e.g., takes time. You can move this to compile time with manual work.
1.If I have larger Database in terms of Table/Entites as described above, Is it a good idea to use Entity Framework?
I certainly wouldn't let it stop you.
2.What will be the better approch using Entity Framework to work with database?
3.Should i create multiple DataContext or EDMX files with lesser entites in it?
That's certainly a good approach for many applications.
4.How will these different DataContext interact with each other?
Mostly not. A single, giant data model is often a bad idea due to service coupling. However, you can selectively couple them by sharing portions of the models with includes in EDMX or classes in code-first.
5.Is there any recommended no of tables that should be used while working with Entity Framework?
One way is to use smaller models, as you've suggested. Another way is to work around the runtime performance issues which sometimes come with larger models (see the links I give above). Like any potential performance "problem", write correct code first, then profile and fix the slow parts. Usually, query tuning is more important than model size anyway.
EF, probably yes. The toolset in Visual Studio? Not so much, apparently. For a database this big, you might want to do Code First.
I think EF itself have't performance limitations for count of tables, but have for count of records in particular table. You have to do manual object-db relation (i.e. manual write classes for tables and corresponding attributes) for go away from design problems in VS10.
It's clear approach in Hibernate, but in EF probably not.
Entity Framework is the best way to develop database applications.
I used to develop my applications using LINQ to SQL but since Microsoft is not going to support it in future, it recommends to use Entity Framework.
By the way, Entity Framework 4 in .NET 4 has much better performance than previous versions.
I'm currently developing an enterprise application using Entity Framework and it supports all my needs.
I suggest to use Entity Framework.

is it that easy working with ADO.NET Entity framework in real programming?

HI Guys,
I was watching these videos series about Entity Framework:
http://msdn.microsoft.com/en-us/data/ff191186.aspx
is that easy building application in real world programming??? and is it ....reliable...has good performance...
"I am a graduate.."
thanks
Entity Framework is a valid real world data access tool. It is very easy to get up and running with EF. You simply import (or create in EF 4) your data model. You then can rename it to make it more code friendly. And then you are off querying databases.
Performance
I have been on multiple projects that use it, some which require high throughput, others that have low performance requirements. Entity Framework out of the box is not the fastest solution in the world, so there are a lot of performance tweaks that have to go on, but its all do able.
Reliability
We never have issues with reliability. We have never had an issue with EF in general, its always data content related. Trying to insert duplicated data, etc.
Other Tangibles
EF follows a pattern which allows for you to do some fun stuff with templates and abstract classes. All entities inerit from a class, entities that have references inherit from other classes. All Entity Contexts inherit from ;) ObjectContext classes, which provide a base set of functionality that allows you to create generic DAO implementations that can be reused throughout the enterprise.
If you are using UI dev, you can also use Data Services that wrap EF, as a fast gateway to your databse. The only downside of this is that you dont have access to the full suite of the Entity Framework.