Using EF 4.1 in MVC 3 environment. I'm also using the POCO generation tool I downloaded using NUGET.
I am looking for a way to "customize" the POCO classes with attributes for validation without losing these changes every time the database changes (and a resulting re-sync is performed).
I've tried creating abstract classes and instantiating an inherited class, but EF forces me to create a concrete class through the EDMX file and this descendant class also becomes a generated POCO which is "refreshed" with every database sync.
I've notice the POCO's were partial classes meaning I could add members to the classes in a different file, but this approach wouldn't let me add to existing members.
While I understand that what I'm running into is a limitation of the database first approach, I suspect that there is a way to alter/customize the POCOs in a way that isnt lost with each re-fresh.
You have at least 2 options:
Implement the IValidatableObject interface on your partial class and provide the Validate method.
As Eranga mentions, use the MetadataType attribute to move the validation attributes to another class with the same properties.
Overriding OnModelCreating will only work for code first and isn't an option in model / database first.
Related
I understand the fact that generating a model based on the DataBaseFirst method woill produce a collection of entitites on the ORM that are essentially mapped to the DB tables.
It is my understanding, that if you need properties from other entities or just dropdownlist fields, you can make a ViewModel and use that class as your model.
I have an AppDev course that I just finished and the author wrote something that if I understand it correctly, he is referring to change the ORM entities to fit what your ViewModels would look like, hence, no need for ViewModels. However, if you do this, and regenerate the ORM from the database, those new entities that you placed as "ViewModels" would be gone. If you changed the ORM to update the database, then your database structure in SQL Server would be "undone".
Please inform me if my understanding is correct that I simply need to use a ViewModel in a separate folder to gather specific classes and or properties in a superclass or a single class with the properties that I just need and use that as my model....
Here is the excerpt from the author:
EntityFramework is initially a one to one mapping of classes to tables, but you can create a model that better represents the entities in your application no matter how the data is stored in relational tables.
What I think the author may have been hinting at is the concept of complex models. Let's say, for instance, that in your Database you have a Customer Table and an Address Table. A one to one mapping would create 2 model items, one Customer class and one Address class. Using complex model mapping, you could instead create a single Customer class which contained the columns from both the Customer Table and the Address table. Thus, instead of Customer.Address.Street1 you could refer simply to Customer.Street1. This is only one of many cases where you could represent a conceptual model in code differently than the resulting data in storage. Check out the excellent blog series Inheritance with EF CodeFirst for examples of different mapping strategies, like Table Per Hierarchy (TPH), Table Per Type (TPT), Table Per Concrete Class (TPC). Note that even though these examples are CodeFirst, they still apply to Entity Framework even if the initial models are generated from a Database.
In general, if you use DatabaseFirst and then never modify the resulting entities, you will always have a class in code for each table in the database. However, the power of Enity Framework is that it allows you to more efficiently work with your entities by allowing these hybrid mappings, thus freeing you to think about your code without the extra burden of your classes having to abide by rigid SQL expectations.
Edit
When the Database-First or Model-First entities are generated, they are purposely generated as partial classes. You can create your own partials which extend the classes that are generated from Entity Framework without modifying the existing class files. If the models are re-generated, your partial classes will still be intact. Granted, using partials means that you have the Entity Framework default behaviors as well as your extended behaviors, but this isn't usually a huge issue.
Another option is that you can modify the TT files which Entity Framework uses to generate your models, ensuring that your models are always regenerated in the same state.
Ultimately, the main idea is that just because the default behavior of Entity Framework is to map the database to classes 1:1, there are other options and you are never forced into something that isn't efficient for your project.
If you're not coding up POCO's and you're forced to use the model generated by Entity Framework or one of the extensions, is there any way to annotate the model other than:
1) Using a view model
and
2) Annotating the model generated by EF, which should of course be ruled out as it will anyway be over-written every time the model is updated or refreshed from the database?
I do not know if I understand your question, but seems you need write DataAnnotatios to Model autogenerated by EF and the DataAnnotations can't be lost when you update the EF. If it is you need see: this post.
First of all I want to ask that what is the difference between Entity Class and our Model Class ?
And when I use to add Data Annotations on the Entity Classes generated by the Entity Framework in Database approach, it's vanished upon every "Update From Database", and for this user defined Model Classes can be used but I have no idea to use them with the generated Entity Classes.
An entity class is a class that directly associate's with a real object and is linked to business logic and holding information about the system. Entities are usually used to establish a mapping between an object and to a table in the database.
Models are simply classes that are associated with a views and controllers which define or contains the definition of an object and when there has been a change in state. These can hold your data annotations to validate before going up to the Business/Data Access layers...
This leads me on to your next question and if using EF to generate your data model classes using the "database first" approach, then you cannot apply the data annotation attributes directly to your classes. Because the EF Designer generates the model classes, any changes you make to the model classes will get overwritten as you have been experiencing. If you want to use the validators with the classes generated by EF then you need to create meta data classes: http://blogs.microsoft.co.il/blogs/gilf/archive/2011/01/20/adding-metadata-to-entities-in-the-data-model.aspx
Hope that helps.
Danny
I'm building an application using MVC 3 and Entity Framework 4.
I've created my Entity Data Model and generated a database from it.
Now I know the validation attributes such as [Required] or [StringLength(5)] can be used on the model properties to provide validation both clientside and serverside.
I would like to know if these attributes can also be generated dynamically instead of having to add them to the model explicitly? I saw that in EF 4.1 RC you can make use of the Fluent API to further configure your model in the OnModelCreating method by using the DbModelBuilder class.
As shown here
I'm working with a framework however that still uses ObjectContext instead of DbContext so I would like to know if the above solution can be used in combination with ObjectContext?
As a final note, since I've been trying to figure out how to generate and use data annotations it seems using view models would increase the complexity of validation. From what I read here it seems that just passing the models directly to the view would remove the need to add annotations to the models as well as the view models. However that means that you can no longer use strongly typed views when you do joins on the models and pass those to the view directly?
No it can't. Fluent API is different approach to describe mapping. You can use fluent API or EDMX (Entity Data Model). Not both. Fluent API also works only with DbContext API. If you want to have annotations generated you can try to modify T4 template generating your classes.
I have come across a disturbing issue when using poco classes that are extending base classes.
For example, let say you have a Person poco class that has a strongly typed Car property. You also have a Spouse poco that also uses the Car Property.
Now you want to display "Person Car" and "Spouses Car" in the view using the Display("Name = xxx") attribute. You cant!!! Becareful of this issue if you are not using flat View Models
I am using Entity Framework and generating my POCO classes via T4 - these classes inherit from nothing and are very plain and simple (created via template in vs 2010)
I tried using the Metadatatype Attribute so I could create a buddy class but when I did this I no longer was able to see my properties... if I removed the attribute! the properties appeared.
Anyway, searching deeper I found this statement from Microsoft
The associated class must be used with EDM or LINQ-to-SQL models because CLR types cannot mark existing properties with new attributes. If you are working with CLR objects directly, sometimes referred to as Plain Old CLR Object (POCO) types, you can apply the attributes directly to the model
So it appears it doesn't work. Anyway it's difficult for me to insert my Data Annotation on the MODEL itself because it's created via T4 hence if I edit it and then re-run the tool it will remove all my changes.
There is a pretty strong consensus around SO and the MVC blogosphere that you shouldn't annotate your business/crud/domain classes with attributes. Not only is your entire MVC stack becoming dependent upon your business/database classes but you'll quickly end up with multiple context scenarios ( same Model, different validation rules ) that are impossible to validate with just a single model.
Use separate view models for your screens, annotate those.
Based on your comment: "Data Annotation on the MODEL itself because its created via T4 hence"
What I'm trying to say is put your dataannotations on your viewmodels, leave your POCO models alone.