Entity Framework: Naming conventions/suggestions for EDMX file and entity class? - asp.net-mvc

I´ve not had much contact with Entity Framework yet and therefore I´d like to hear some guys with experience.
I´ve got an MVC project and my DataAccess lies in a different project where I want to place my EDMX file.
So how would I like to name this file? Per default it is "Model1.edmx" but in the context of MVC I don´t feel comfortable with this name. Is it really a Model?
I tend to call it "DbModel" or something to indicate that it is database related stuff.
And how do you guys call the entity class? I think I like the EF typical name "DbContext".
So within my controllers I´d have something like
public class WorldController : Controller
{
DbContext db = new DbContext();
public ActionResult Own()
{
var allContinents = db.Continents;
[...]
}
}
Sorry for being fussy but I really do care about naming.

It is good to care about naming!
How to do it depends on the composition your application. Let's say you have a web application for registering UFO sightings, to name something common. If there is a separate part of your db (maybe a separate schema) containing users, roles and permissions, you could create a context named AuthorizationContext, and for the business part a context named UfoDbContext.
I mean, if there are clear aggregates with no or little overlap you could create separate contexts for them with clear names. If one context fits the bill, I would still give it some meaningful name (not DbContext) that relates to your application domain.
There are people (I'm not one of them) that like to work with one context per application "column" (db to UI) or "user story". Meaningful names are even more important then.

My suggestion would be to use something that indicates the contents in the naming. You could take part of your project name, for instance, and bring it down into the name of the EDMX. Include something that makes it less generic.
I also tend to include an "Ef" in my naming, which I started when working on a project that already had an existing ORM.
To take Microsoft's prototypical example: if your project fell under the umbrella name of Norwind, here's how I would name some of the files in my model project:
EDMX File:
NorwindEfModel.edmx
Generator/TT File:
NorwindEfDbContext.tt
Entities class:
NorwindEntities
I can't say this is exactly how Microsoft would have it if you downloaded a sample project from them (though I believe it would be similar), but I think it's a reasonable naming structure and it fits my needs. The bottom line is this largely comes down to opinion and your need for specific distinction.

Related

Domain Driven Design - Using code first approach

Is it good practice to create a database from a domain model, using a code-first approach, which then dictates what the database schema looks like (using entity framework). Or should you always design the db first and then create you domain model(s)?
From 2009 to 2013-ish, that's exactly what I have done (and answered many SO questions doing exactly that!) - using Entity Framework as our "Aggregate Roots" and extended them from there with value objects (poco classes) and so on.
I am here today to tell you this: DON'T DO IT!
The latest "rutt-rough" coming from DDD in C# is how most of us have done this - a direct "Table to Entity/Aggregate" mapping. All this does is give a false sense of separation without any bounded contexts.
In the past, I usually created a folder called, say, "Users". I also had an entity called User.cs for code first (or in the designer, a table called User). I was allowed to add my own methods and properties onto a User.cs partial. I would also group all value objects related to users within a subfolder. So, it looked like this:
\Users\
^- User.cs partial with additional so called "logic"
- UserService acting with "business logic" on User and related properties.
\users\EmailTemplates\
^- I often needed a way in DDD to store other "Entities" related to this AR.
\Users\ValueObjects\
^- UserAddress.cs
- UserTarget.cs
- UserTypeEnum.cs
- // basically a dumping ground
Now, after a year, we've come to realize that we have so much work on UserTarget that it is huge. It is becoming a huge service-like class with 1000 lines of code. In DDD, this really should be it's own bounded context, called UserTargets and act as its own aggregate root, with many value objects in it. But yet, there isn't anything stored in the DB. Do we create a entity in code first? have an exception in attributes to ignore it? etc.
It just feels so dirty and hacky any way you cut it.
Let's take another example out of the DDD playbook:
Biz: "I have a user that needs to signup. Once they signup, they will have a project."
Dev team: "Great, we have the following entities: User and Project"
public class User {
public List<Projects> Projects { get; set; }
public Team Team { get; set; }
}
public class Team {
public List<Projects> Projects { get; set; }
}
public class Project {
public User Administrator { get; set; }
public List<User> Members { get; set; }
}
That alone is a problem. Now that we are using CQRS/event sourcing often, it's easier to model it more like:
User : AggreateRoot
Team : AggregateRoot
Project : AggregateRoot
UserProject : AggregateRoot
UserSignup : AggregateRoot
TeamProject : AggregateRoot
...etc
Note the additional aggregates? How would you represent them in the DB? FKs right? Well, what if there are additional properties like a TeamProject.ContestEntrySubmitted datetime? Ah yes, now those FK child tables get ugly in EF and code first.
The domain is for your pure business design - to solve solutions. Not for how many POCOs you can organize to make EF happy in code gen. Not as your CRUD layer to bypass all business logic, new up an ObjectContext, and call Save(new User()). I see developers wasting so much time with this or that EF issue, wrestling with "do we side-step DDD to make EF do this? or do we spent a few days changing EF's internals and T4s to do that instead? we'll remain DDD-ish, but many that's a lot of work."
So I am hear to ask, "Why do it at all?" Separate the domain from any storage model.
In CQRS, your "Domain" is write-only anyways. Having them as a EF objects already throws event sourcing out the window, and now forces you to handle states.
By freely writing domain aggregates and entities allows us to bind multiple projects, or users, to each other without affecting the other aggregates. if the other aggregates, say User, wants to have a project count, sure, listen for the ProjectCreated event for that userid who created it and ProjectCount++ and call in the day.
The point is, once you apply DDD to Event Sourcing patterns, you look at your domain quite differently. It is no longer a "stateful" domain in a sense that you can query anytime to get the last 10 years who signed up, or knowing you can just go to the DB and run that SQL. No, instead it is more like, "I need to make a state change to X entity. It will be caused by this, this and that when in these specific states. Now, when the planets have aligned, we'll change the Username to be this in a new ChangedUSernameBecausePlanetsAligned event."
I guess my point I am trying to make is going down the EF Entities-as-DDD AggregateRoots feels so dry in the end, and without any DDD substance. You end up with nearly 30 or 50 "aggreateroot" folders in your monolithic MyProject.Domain assembly. And is what Udi basically calls, a Big Ball of Mud.
My general rule now is not to use any frameworks for my domain - freeing me up to structure it in pure DDD as I see fit, and it has been really enjoyable. There are no confining frameworks or restrictions. I've actually re-written entire domains in F#, just for fun and since there was no need for any "queries", it just happened.
Then, wjem moving into the Event Sourcing world, you start to realize exactly why your domain is "write only" and think about how you can "push" data to the views, instead of giving the views something to query from your domain. Removing that Querying part from your domain really makes this nice and neat.
--
Eh, I think I just realized that I wrote an answer that basically says, "Hey, don't do Entity Framework and DDD. Check out CQRS and DDD instead." LOL

How many DbContext subclasses should I have, in relation to my models?

I'm learning ASP.NET MVC and I'm having some questions that the tutorials I've read until now haven't explored in a way that covers me. I've tried searching, but I didn't see any questions asking this. Still, please forgive me if I have missed an existing ones.
If I have a single ASP.NET MVC application that has a number of models (some of which related and some unrelated with each other), how many DbContext subclasses should I create, if I want to use one connection string and one database globally for my application?
One context for every model?
One context for every group of related models?
One context for all the models?
If the answer is one of the first two, then is there anything I should have in mind to make sure that only one database is created for the whole application? I ask because, when debugging locally in Visual Studio, it looks to me like it's creating as many databases as there are contexts. That's why I find myself using the third option, but I'd like to know if it's a correct practice or if I'm making some kind of mistake that will come back and bite me later.
#jrummell is only partially correct. Entity Framework will create one database per DbContext type, if you leave it to its own devices. Using the concept of "bounded contexts" that #NeilThompson mentioned from Julie Lerhman, all you're doing is essentially telling each context to actually use the same database. Julie's method uses a generic pattern so that each DbContext that implements it ends up on the same database, but you could do it manually for each one, which would look like:
public class MyContext : DbContext
{
public MyContext()
: base("name=DatabaseConnectionStringNameHere")
{
Database.SetInitializer(null);
}
}
In other words, Julie's method just sets up a base class that each of your contexts can inherit from that handles this piece automatically.
This does two things: 1) it tells your context to use a specific database (i.e., the same as every other context) and 2) it tells your context to disable database initialization. This last part is important because these contexts are now essentially treated as database-first. In other words, you now have no context that can actually cause a database to be created, or to signal that a migration needs to occur. As a result, you actually need another "master" context that will have every single entity in your application in it. You don't have to use this context for anything other than creating migrations and updating your database, though. For your code, you can use your more specialized contexts.
The other thing to keep in mind with specialized contexts is that each instantiation of each context represents a unique state even if they share entities. For example, a Cat entity from one context is not the same thing as a Cat entity from a second context, even if they share the same primary key. You will get an error if you retrieved the Cat from the first context, updated it, and then tried save it via the second context. That example is a bit contrived since you're not likely to have the same entity explicitly in two different contexts, but when you get into foreign key relationships and such it's far more common to run into this problem. Even if you don't explicitly declare a DbSet for a related entity, it an entity in the context depends on it, EF will implicitly create a DbSet for it. All this is to say that if you use specialized contexts, you need to ensure that they are truly specialized and that there is zero crossover at any level of related items.
I use what Julie Lerman calls the Bounded Context
The SystemUsers code might have nothing to do with Products - so I might have a System DbContext and a Shop DbContext (for example).
Life is easier with a single context in a small app, but for larger application it helps to break the contexts up.
Typically, you should have one DbContext per database. But if you have separate, unrelated groups of models, it would make sense to have separate DbContext implementations.
it looks to me like it's creating as many databases as there are
contexts.
That's correct, Entity Framework will create one database per DbContext type.

Which layer should i place .edmx and generated POCO classes?

This is regarding a layered design with EF DB First model.
So far i have not used Entity Framework before, used only Entities and placed on a different project with Domain/ DTO sub folders. Also referred the same in DataAccessLayer, Business Layer and MVC application and written a code with usual ADO.Net queries and prepared POCOs of my entities. No issues.
Now we are developing an application using Entity Framework DB First model. We choosen this DB First model, as the DB Design is not in our control. It is done by DBA.
I thought of reusing the old simple design here. But not sure where/which layer I should exactly fit the edmx file and the generated POCO classes. I didn't find any samples with layered architecture style uses DBFirst approach.
I referred this. http://aspnetdesignpatterns.codeplex.com But they use NHybernate
Here is the highlevel overview of old design.
Any suggestions on design/samples, please you are welcome.
Edit:
From the below answer, I think the entity framework produces the POCOs we could rename existing Entities/Domain layer to Domain Layer and putting the generated POCO classes there. Also we can simply keep .edmx in DataAccessLayer with the list of IRepository classes that wraps EF for TDD. Does this makes sence? or any valuable points?
Update:
Currently i removed DataAccessLayer and keep only Entities layer which
has a model.edmx file and classes generated by EF and also all
Repository classes implementing IRepository. I refer this into
Business Layer, MVC as well. Am i doing right? I feel like i am doing
a bad design :( Please suggest/help
Because you're unfortunately severely handicapped by the decision to create the database first, you will need to use an Anti-Corruption layer per Eric Evans' Domain-Driven Design.
This is a good solution for what to do when you're given a shitty interface that you absolutely must code against - make an interface wrapped around the DB that behaves the way you want it to. Do not expose any EF classes directly to anything except the anti-corruption layer itself.
Here's a reading example:
public class SomeReadService : ISomeReadService {
public SomeViewModel Load(Guid id) {
using (var dbContext = new DbContext()) {
// Query the DB model, then *map* the EF classes to SomeVieWModel.
// This way you are not exposing the shitty DB model to the outside world.
}
}
}
Here's a writing example:
public class SomeRepository : ISomeRepository {
public SomeDomainObject Load(Guid id) {
using (var dbContext = new DbContext()) {
// Map the EF classes to your domain object. Same idea as before.
}
}
}
I would still try to demonstrate to the client that having a separate team design the DB will be a disaster (and my experience strongly indicates that it will). See if there is some way you can provide the feedback that will demonstrate to the client that it would be better if you designed the DB.
Please see the SO link for similar kind of question below:
With a database-first approach, how do I separate my Core and Infrastructure layers?
Hope this helps !!
In my opinion, Entity Framework used correctly negates the need for a seperate DAL. I think of EF as my DAL. It allows you to concentrate on the business part more. EF does all the data access code for you. You can simply use your EF context in your business layer. To me, this is one of the best benefits of EF; that it is your DAL.
Depending on how you separate your layers (different assemblies or different folders within an assembly) depends where you put your POCO classes. If different assemblies (which is overkill for most projects) then a 'Common' assembly referenced by all others is the place to put POCO classes. If different folders, then a folder named 'Models' or 'DomainModels' is the place.
Specifically for an MVC application, I would put my POCO classes in the 'Models' folder (I also have a 'ViewModels' folder), and my .Edmx in a BLL folder which I sometimes call 'Logic'.
If you need a loosely coupled architecture for testing, then a folder named Repositories with the EF context wrapped in your own repository pattern is the way to go.
Edit:
The Short Answer is Data Access Layer (DAL)
You need to Enterprise architecture and it changes according your needs, but in your case Model Driving Design Pattern is the solid solution.
You can use MVC and you can drive your model from Poco or other entities like NHibernet etc.
No any importance about code-first or db-first, it is interesting just with the architecture creation phase.

ASP.NET MVC - is it okay to have sideline presentation logic?

In most documentation you read about ASP.NET MVC, the entire 'Separation of Concerns' is very heavily pushed. Dependency Injection/Inversion of Control, Unit Testing, keeping 'logic' out of the Views, etc.
But how far is this intended to be pushed? Is it bad practice if a specific task requires extra logic beyond the 'three layer' approach of View/Model/Persistence?
For example, I have a solution set up with four individual projects.
Project.Web (ASP.NET MVC) [ References Data.dll, Models.dll ]
Project.Data (Fluent nHibernate Mapping) [ References Models.dll ]
Project.Models (POCO, Helpers, Factories, etc)
Project.Tests (Unit Testing)
Up until now, this has served me pretty well. But I require some very abstract logic for some of my MVC Views, such that I need to take part of the Models and arrange a View Model that is persisted in the database.
This cannot happen in my Data section, as that would dispose the re-usability of it, and there is business logic included in the process. It cannot entirely happen in my Models section, because that would require it to have knowledge of the Data section, which it does not. And I do not want to put it in the Web section because I don't want data access code there.
Question
Is it in massive violation for me to add, say, a Project.Presentation project that references Data.dll and Models.dll to construct what I need to? Moreover project concerns aside, is this a bad approach in general or is this something a lot of you find yourselves having to do at times? Part of me feels that if I am having to resort to this, then I've just built my software wrong - but at the same time I am very confident I have done a fairly good job, it is just too abstract to make a raw HTML interpretation of without middle-man arrangement.
It's been my experience that single responsibility is a great way to write code you expect to change early and often. Like Jan, I too have a solid line between who does what, when. The more you enforce this, the easier it is to replace an slice of your system. I recently removed linq2sql with EF4.1 and because of SRP, once I got the tests passing around my new EF4 layer, everything else just worked.
That said, I typically let unit testing dictate where these things live -- it's my driver for SRP as well as asking the basic question "must =class/service= know about =something else= to do it's job?" If the answer is no, it goes somewhere else -- if yes, it's a dependency. Now, if it becomes painful, that's its way of telling me "this is stupid" (see this question for the stupid) and I've attempted to force something instead of allowing it to fit the way it must.
Onto your core queston : you've clearly identified a gap in your code -- it MUST know about two things (data and model) and I agree, it should be its own thing and pulled out. I would call this a "DomainService" or maybe just DTO, but presentation feels like it would be doing more than just prepping data. (I'd argue the view handles the presentation ... maybe you simlpy mean presenter?). I would also argue against your perception that you did "something wrong" - no, you're learning to write code differently and allowing it to evolving, EXACTLY as it should. :-)
I use the following structure, which more or less solves all problems we've had regarding MVC structures.
Models: contains all ViewModels. Just clean, only getters and setters.
Business logic implementation: Set of projects that contains database logic, DAL entities etc. But only has one interface (in our case this is a WCF API).
ServiceLayer: the bridge between Business Logic and ViewModels. Doesn't know anything about web.
Mapping layer: translation between business entities and ViewModels.
Web project: holds very thin Controllers and Views, and everything web related.
A web page flow will follow this flow:
URL maps to a certain Action
Actions are really clean, they only reference a method in the ServiceLayer
The ServiceLayer executes one or more actions in the Business Logic Implementation (get data, store data, etc.)
The ServiceLayer passes the business entities to the Mapping Layer.
The Mapping Layer translates business entities into ViewModels
In code this would look like:
// action
public ActionResult ListOfObjects () {
var model = new ServiceLayer.ObjectsClient().GetListOfObjects();
return View(model);
}
// Service Layer
public ListOfObjectsModel GetListOfObjects () {
var businessEntities = BusinessDao.GetThingysFromDb();
var model = Mapper.TranslateToViewModel(businessEntities);
return model;
}
// Mapping Layer
public ListOfObjectsModel TranslateToViewModel(List<BusinessEntity> entities) {
// do mapping
}
When handling POSTs you will follow the same flow, but the mapping layer should translate your ViewModel into Data Entities that are given to the Business Logic.
"take part of the Models and arrange a View Model that is persisted in the database"
Then its not a viewmodel.
Does that simplify things?
What is a 'ViewModel':
More than often 'ViewModel' is confused with persistence. If you look at the word more closely it is a combination of 'View' + 'Model' - which essentially means it is a single unit of data that is required to fulfill all the needs of your view. A ViewModel can infer multiple entities or sources to build what is required by the View.
Now Coming to your question:
Is it in massive violation for me to add, say, a Project.Presentation project that references Data.dll and Models.dll to construct what I need to?
Re: If I had to do it, I would have created a seperate namespace (folder) in my MVC project named 'ViewModels' and placed all my Viewmodels in there. In my opinion if you want your ViewModels to be in a separate namespace, it would not actually violate MVC. You are just incresing the separation or making it more unit test friendly.
Just my 2 cents!!!

Use of "stores" within a web application

I see heavy use of "store" objects in the web app I am working on. Is there a name for this pattern and would you say these types are in the BLL or DAL?
These stores contain fragments of what I would consider a classical DAL type, associated with a single type.
For example, we have a TabStore containing methods for the persistance and retrieval of Tabs. Within each method in the TabStore there is code to invoke the appropriate NHibernate query.
What are the pitfalls (if any) of working with this pattern? Is it really a simple attempt to separate what might once have been a monolithic Dal type into more manageable, smaller types?
Example method:
public IList<Tab> GetAllTabInstancesForUserId(Guid userId)
{
IList<Tab> tabInstances =
UoW.Session.CreateQuery("from Tab t where t.UserId=:userId order by t.TabOrder")
.SetGuid("userId", userId)
.SetCacheable(true)
.List<Tab>();
return tabInstances;
}
It may be what is more commonly known as a Repository.
The abstract Repository belongs in the Domain Model, but should be implemented by concrete classes in a separate Data Access Component.
If I understand the question correctly, "stores" are more related to DAL than to BLL, since there should be little logic in them - after all their role is just "storing".
Some more details would definitely be helpful, including code snippets where the 'store' is used...
But based on what you have in your question, it sounds like the developers used the term 'store' instead of 'Repository' which implies the Repository Pattern (which are related to your Data Acess Layer).
After your update...it definitely seems like what the developers originally called a 'store' is a 'repository'.

Resources