Compare Entity Framework 4 objects to ADO.NET C# POCO Entity Generator objects - entity-framework-4

I really have two questions:
What is the difference between an Entity Framework Entity object and an ADO.NET C# POCO Entity.
Do I have updating a record using a repository correct below?
If you turn off code generation, then add the ADO.NET C# POCO Entity Generator, it provides a nice class representation of your Entity Framework 4 objects. The idea is that (from here):
The POCO Template can be used to generate persistence ignorant entity types
from an Entity Data Model.
However, these objects have the relations between objects as well as a link back to the database. For example, you can pull one out of your repository, alter it, then save changes at the repository or unit of work level, and it saves the content to the database.
So my question is what is different between a native Entity Framework object and these POCOs generated using this tool?
This is what I think when I update a record using a repository. Is this wrong?
Request a POCO from the repository.
The Repository loads the records from the data context, creates a new POCO for each record found, copies the values from the Entity Framework objects to the POCOs, and returns a collection of the new POCOs.
Changes are made to these POCOs outside of the repository, then the POCOs are submitted back to the repository using something like Save(POCO).
The repository loads the matching records from the database and copies the POCO properties to the Entity Framework objects.
One calls Save using either the repository object or unit of work object.

In case of POCO generator the generated entity classes (eg, Employee, Company etc.) don't derive from any special class (hence called Plain Old).
Whereas in case of entityobject generator, the entity classes derive from the special 'EntityObject' class, which provides certain capabilities.
The objective behind having POCO classes is to do away with the DB specific concerns of an entity. Thus keeping our domain model unaware of DB/persistence operations.

POCO means that you have a plain old CLR class which is not polluted by special constructs related to the persistance. Entity objects are derived from EntityObject class and they use a lot of classes and attributes directly related to entity framework. When using EntityObjects you are making your code fully dependent on entity framework.
What you describe in your repository was used in EFv1 to achieve POCO approach. Currently you can use POCOs directly. POCOs don't have any relation to the database. In some scenarios POCOs are dynamically proxied by EF dependent constructs but this happens during runtime so it doesn't pollute your code.

Related

In Breeze for .NET, how do you save DTOs alongside Entity Framework entities?

In the official documentation, it's mentioned that DTOs can be used as breeze entities:
It does not have to be an ORM class. It could be a DTO class that you will later map into a class in your business model via your implementation of BeforeSaveEntities.
In a comment by Ward Bell, he suggests the following strategy for saving DTOs alongside EF Entities:
Remove DTO from EntityInfos
Retrieve corresponding business model entity from Db (or create such an entity if this is an insert)
Update this copy from DTO
Add this entity to the EntityInfos (don't forget the OriginalValues properties for an update)
Rinse and repeat for all such DTOs
Let it go ... and EF will save it
Intercept the "after save" and remap the updated/inserted business entity into its DTO form in the SaveResult so that you send the DTO, not the "real" entity, back to the client.
The problem with this recommendation is with step 4. The EntityInfo.Entity property is defined as internal. How can you create an EntityInfo with the proper EF Entity?
One alternative to this recommendation would be to override the SaveChangeCore method and handle the mapping of DTOs to EF Entities in that method. The downside to this is that the EFContextProvider.SaveChangesCore has a lot of code and I'd rather not duplicate that effort.
I found ContextProvider.CreateEntityInfo(). It has an overload that accepts an entity and sets the EntityInfo.Entity property.

EntityFramework database vs model

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.

How to use entity framework in other modules?

I am currently developing project using C# MVC and entity framework, I want to use the entity framework in other modules ,
i.e security module , Utility module ,
i want to call the db using the entity frame work, how do i do this ?
i am new to this are please explain in detail, idea is to break the project into presentation layer, business layer and data access layer..
i don't know how to archive this.
Try this way,
There are three ways to work around entity framework, Database First, Model First & Code First.
Database First: If you already have database, then entity framework can generate a data model that consists of classes & properties that correspond to existing database objects such as tables & columns.
The information of database structure, conceptual data model & mapping between them is store in the xml in an .edmx file.
Model First: If you don't have database, you can start creating model using vs entity framework designer. This approach also use the .edmx file.
Code First: In this approach, we don't need .edmx file. Mapping between store schema & conceptual data model is represented by code, handled by code convention & special mapping API.
Here I have used the Database First approach.
In order to use the Dal class lib, add the reference in the business logic layer and initialize the entities class. For example
Find the entity framework object.
Initialize the entity framework object in other class lib.
FrameworkEntities entities = new FrameworkEntities();
Please let me know, if you want to use model first or code first approach.
Get started from the below link for the Entity Frame Work
http://msdn.microsoft.com/en-US/data/ee712907?

How to use Entity Class with our Model Class in ASP.net MVC

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

ASP.NET MVC 2 Validation: Metadatatype can't be added to standard POCO CLR classes - what's an alternative?

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.

Resources