POCO entity Fluent API versus Data Annotations [duplicate] - c#

This question already has answers here:
Mixing Fluent API and DataAnnotations in EF code first
(3 answers)
Closed 4 years ago.
I am coding our POCO entities in a Domain project in which I have no references to either EntityFramework or DataAnnotations. A second project, DataAccess, contains the data context and fluent configuration of entities.
Some entity properties are IsRequired or HasMaxLength. Developers using the Domain will not know what is required or if there is a maximum length of the property without Xml commented documentation. So, I've added documentation to the properties to convey the requirements.
The problem is, however, if a requirement changes I have to update the comments. This means that I'm updating 2 libraries - Domain and DataAccess.
I've been apprehensive in referencing DataAnnotations in the Domain; there are no attributes on my properties. These attributes would give a developer with access to the Domain entities knowledge of what is required or if there is a max length for a property.
Is there another way to convey property requirements for properties without using DataAnnotations on the entities or having to update the Xml comments on the entities?
Or, am I being unnecessarily thick-headed about adding the DataAnnotation reference to the Domain project?

I think it can be a good idea to leave your POCO entities without annotations and without including reference to EntityFramework.dll. Easier to create portable dll and reuse your model. That is, if you ever going to need it.
But as you said it makes it harder to have "auto documented" model. You could try with generating model diagram out of DbContext, there is a power tool for that. Maybe that will be enough for your documentation needs. I tried it on a model with >200 entities and it worked ok. For the diagram generation it took cca 2min but after that it worked ok and was useful for "documentation" purposes.

Related

Can we use SQLMetal Objectmodel as application object model?

Our team has just started using Sql Metal and I have been playing around with it for 2 days. While doing this, I have noticed couple of things.
When we run command like following
sqlmetal /code:ps.cs /server:devapp042dbs
/database:promotionalsponsorship /namespace:DAL
It creates a "LINQ to SQL SQLMEtal" object model. Now, this is not our regular class. It has a lot of autogenerated code and it almost smells like LINQ/EF with a lot of autogenerated properties and methods.
I have used Micro ORMs like Dapper and ORMLite from Service stack and the onderful thing about those is that it works with the simple objectmodel that we have created rather than auto-generating its own object model.
My question is that can we use these SQLMetal mapping classes as our Models of the application or we have to create a simple wrapper class around it using which we can extract all the information that we need to.
To clarify my point following are the samples of what I call a SQL Metal Class and a simple model class
Although this question would possibly be closed, as the answer is subjective, the short answer is yes, it is perfectly valid to use such autogenerated set of classes as your model. There are plenty of succesful apps built this way.
Since these classes are partial, you can even extend your domain model by adding custom properties/methods/events.
If you are concerned that the autogenerated code is not clean enough, consider the code first approach of the Entity Framework, nHibernate or any other ORM that supports this scenario. This way you start from a clean POCO model and just define its mapping to a relational structure.

Add Entity Framework Data Annotation to Another Project's Class

Let's say I have a set of classes that I want to share across multiple projects. For instance, I could use them in a REST service and also in a client that consumes that service.
So I create the following projects:
MyOrders.Models
MyOrders.RestApi
MyOrders.Client
Both the RestApi and Client projects have dependencies on the Models project.
The RestApi is using Entity Framework (code first) so normally you'd decorate the model's properties with things like [NotMapped] and [Key]. However, I don't want the Client solution to have any dependency on Entity Framework. None. So I can't decorate the models' properties with EF-specific attributes.
So my question is, is there some way to correctly set the models' EF-specific attributes from the RestApi project instead, maybe in the Context's constructor or something?
You can have the POCOs in your Models project, keep them totally ignorant of Entity Framework, and do the mappings in a separate project or in the RestApi project itself.
You can do this by the fluent mapping API, for instance in the OnModelCreating override of the context that you create in the EF-aware project:
modelBuilder.Entity<Order>().HasKey(o => o.OrderID);
modelBuilder.Entity<Order>().Ignore(o => o.OrderTotal);
etc.
This is a good argument for using custom Data Transfer Objects that are independent of the table-like entities. Although it can feel like overkill to have nearly duplicate classes - one as DTOs and one as EF Entities - there is another long-range benefit: the two sets of classes can vary independently. Let's say that you change the table table structure, but the client doesn't need to know about this change. Update the EF Entity but you leave the DTO alone, though you may have to update how you map from EF to DTO.
Speaking of mapping: EmitMapper can be a great help in transferring between the two types of objects.
You need to split your data access models from the rest of the application using Data Transfer Objects.
This will give a lot of benefits. At first it will look if your duplicating all the code of the model. But when your application grows, you will find that need the data in a view which is formatted in another way than how it was or is stored the database. Validation attributes can be added in a very specific way just the way you need it.
Mapping in between them can be done various ways. By hand or by using a tool like AutoMapper

Entity Framework understanding [duplicate]

This question already has an answer here:
ORM Entities vs. Domain Entities under Entity Framework 6.0
(1 answer)
Closed 7 years ago.
I start using Entity Framework about a year ago using Database-First approach. While reading and doing research online, I came across some terminologies that are confusing me. I was wondering if someone can help clear up some questions I have:
1) Using Database-First approach, I build my SQL Tables and create my edmx file from the database. From there, I start coding by create a Data Context and then accessing the entities. I recently read and see that I can right click in the .edmx file and "Add Code Generation Item" and then add "Ado.Net EntityObject Generator/EF 5.x DBContext Generator/EF4.x POCO Entity and etc. What is the purpose of these different code Generators? Am I suppose to implement them? When should I implement them?
2) I'm reading a lot about "object model and domain model". Is EF an object model or domain model ORM?
Thank you in advance for any information.
Add Code Generation Item
By default classes are generated with the help of EntityModelCodeGenerator. With the help of custom code generation, you can customize this. Why you would want to do ?
One example I could give from top of my head is - if you want to implement INotifyPropertyChanged interface by every single entity generated by EDMX. By default EntityModelCodeGenerator would not do that for you. Thus, you would want to customize this.
(Please note this is just my theoretical knowledge however the above example is quite a practical situation)
Domain Model vs Object Model.
Regardless the difference one thing for sure is Domain Model is Object Model too because in both cases you are defining classes, and association. This is how I define Domain Model and Object Model.
The only major difference could be how you are defining objects; in case of Domain Model, you are completely thinking from Business point of view and defining your objects.
From what I see that it is probably EF Database first is Object Model because when I am doing Database designing I am less thinking about Business, rather I am thinking about what is to be stored.
If am making POCO then I probably will be thinking from Domain Model point of view.
In case of EF - Code First, I have started thinking from Business point of view and make my association, then after I think of how objects will be stored.
So it is just a perception and at the end whether Domain Model or Object Model, ORM i.e. EF will provide you to persist this object into the database.
I hope it helps.
You don't normally need to use the "Code Generation Item" option. It is used to perform changes in the version of EF being used, and you could use it to do some custom code generation. In general, you should be able to leave this option alone.
EF is really an ORM (Obect-Relational Mapper). It takes objects and maps them to relations (tables). It can be used as either an object model or domain model (or both) as well depending on how you define those terms.

EntityFramework (ORM) object names and domain model names - how to avoid duplicates?

Let's say I have a project where I use Entity Framework, but I want to use my own classes instead of the EF classes.
Reasons for using my own classes:
Easy to add properties in code
Easy to derive and inherit
Less binding to the database
Now, my database has table names like User and Conference.
However, In my domain project, I also call my files User.cs and Conference.cs.
That means I suddenly have two objects with the same naming, which is usually very annoying to work with, because you have to use namespaces all the time to know the difference.
My question is how to solve this problem?
My ideas:
Prefix all database tables with 'db'. I usually do this, but in this case, I cannot change the database
Prefix or postfix all C# classes with "Poco" or something similar
I just don't like any of my ideas.
How do you usually do this?
It's difficult to tell without more background but it sounds like you are using the Entity Framework designer to generate EF classes. This is known as the "Model First" workflow. Have you considered using the Code First / Code Only workflow? When doing code first you can have POCO classes that have no knowledge of the database, EF, or data annotations. The mapping between the database and your POCOs can be done externally in the the DBContext or in EntityTypeConfiguration classes.
You should be able to achieve your goal of decoupling from EF with just one set of objects via code first.
To extend the above answer, the database table name User (or Users as many DB designers prefer) is the identifier for the persistence store for the object User that's defined in your code file User.cs. None of these identifiers share the same space, so there should be no confusion. Indeed, they are named similarly to create a loose coupling across spaces (data store, code, development environment) so you can maintain sanity and others can read your code.

Validation framework for EntityFramework [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Entity Framework Validation
Is there any good and flexible validation framework for EntityFramework ?
Entity Framework provides a great variety of validation features that can feed through to a user interface for client-side validation or be used for server-side validation.
When using code first, you can specify validations using Data annotation or fluent API configurations.
Additional and more complex validations can be specified in code and will work whether your model hails from code first, model first or database first.
Here are some links for more details: Configuring Properties and Types with the Fluent API and Entity Framework Validation.
You could look at Fluent validation framework. It is not EF specific but means you can use it on viewmodels as well.
You can also look at foolproof validation it does client side validation for things like one property being required if another is true etc. E.g if married checkbox is checked you must add maiden name
Also look for data annotation extensions on nuget it extends what EF offers

Categories

Resources