Using of Entity Framework T4 POCO - c#

I have been using Linq-to-SQL for a while to get access to my database. But I have recently been told this way of doing was not the best one since it allows to mix the data access & business logic layers.
I heard that Entity Framework T4 POCO was a solution but I cannot find complete information about it. Does anyone have more details to share with me ?
Thanks in advance

What a POCO (Plain Old CLR Object) does it that it allows you to create your own representation class of your database. Entity Framework then converts your database (through a configuration (hint use an edmx file)) to the by you created POCO classes.
Example:
Table User:
id | fName | lName | otherField
You can represent this in your C# with a POCO to a user object with the following properties:
int id, string fName, string lName, var otherField.
Then you can, in the getters and setters of these properties, insert your business logic.
NOTE: I'd recommend using just the Entity Framework icm with an edmx file. And put your business logic somewhere else. When creating a web service I always like the following order of classes :
A class that receives the calls and calls the right functions of the next class
This class then converts the given params in the call into a format that the rest of the application understands and calls the right functions of another class.
This class then checks the business logic in the params and calls another class to do something with the database.
This class then handles the database connection and stuff (with use of the Entity Framework) Note again: you can also use POCO's in this last step ;)

See that: Entity Framework - Generating Classes
There is a tutorial how to generate POCO Classes by existing database.

I find this site gives a great example on how to use EF4 with POCO classes.
http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx
This describes the 'code first' approach for Entity Framework 4

Related

how to generate the Repository and model/entity classes with all CRUD operations using database-first apporach in C#

I have a database for which I want to generate the repository and entity/model classes with all CRUD operations.
To achieve this I found a tool, named Entity Developer
(https://www.devart.com/entitydeveloper/download.html), which is generating all the stuff, but without CRUD operation for each entity as tools is generating just an empty class named ABCRepository, so again I have to write the code for each repository class. Though same task can be achieved from Entity framework, except than the repository classes( which does not contain any CRUD operations).
Can any one help me to get the solution?
Update: I have followed this tutorial (https://dzone.com/articles/implementing-the-repository-pattern-using-c-and-en), according to this, Entity Developer should generate the "Repository per entity type" with operations, but while following and creating the Data Model, I get only empty ABCRespository and IABCRepository classes. I tried multiple ways to create the Data Model, yet not successful.
To achieve this I found a tool, named Entity Developer (https://www.devart.com/entitydeveloper/download.html), which is generating all the stuff, but without CRUD operation for each entity as tools is generating just an empty class named ABCRepository
Please check the Generate Partial property of your Repository And Unit of Work template. If it is set to True (by default), the code is generated in ABCRepository.Generated.cs. The code file ABCRepository.cs is created for user code that will not be overwritten by the designer.

Entity objects to business object

I'm working on a new project and wanted to use MVC and entity framework. For the purpose of separation of concerns. I plan to structure my project like so..
MyProject.Web (this project houses the V and C of MVC)
MyProject.Model (this project houses the M of MVC so that it can be reused and shared. This is where my business objects/ domain objects live)
MyProject.BLL (this is where I write my business logic and make available via an interface)
MyProject.Entity (this is my DAL - where entity objects will be generated by the wizard using db first approach)
My question is what is the best way to convert entity object to business object in my BLL? My mapping requires that I join two tables and compute a sum that would map to a field in a business object.
Not sure this is a good example but let say I join customer table and order table and got two records back for the same customer. One is for order placed in the AM and one for order placed in the PM. I need to compute the total for the day and mapped it to a field in my business object.
Automapper comes to mind instead of manually code DTO, but I am not sure if it can do complex mapping (with the sum calculation)?
Is there a way to manually configure custom map in EF 6 to do this?
With Automapper, you can use Projections for complex mappings or use AutoMapper's QueryableExtensions helper methods.
See Aggregations section in the following link.
LINQ can support aggregate queries, and AutoMapper supports LINQ
extension methods
https://github.com/AutoMapper/AutoMapper/wiki/Queryable-Extensions

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

C# class to Sql table

There are a lot of Sql table -> C# class methodologies, but I'm looking for the reverse.
Hypothetical situation:
I have N classes populated by some web service I consume, manipulate, then preform an action on. Now the boss wants said web service data persisted in a database.
I already have the classes defined, how can I quickly and easily (aka, lazily) generate a sql table off of each class?
Entity Framework and nHibernate both allow you to use them in "code-first" mode, which involves writing classes then generating databases.
There is a walk-through of this on ScottGu's blog here: http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx
you can use MS Entity Framework Code First approach:
Code First allows you to define your model using C# or VB.Net classes,
optionally additional configuration can be performed using attributes
on your classes and properties or by using a Fluent API. Your model
can be used to generate a database schema or to map to an existing
database.
read more about it here: EF 4.1 Code First Walkthrough
Entity framework 4 has a code first development feature, I haven't used it so can't really recommend it
ScottGu blog

Understanding Entity Framework classes

I am working on a project where we need to fetch data from a WCF service. The service code looks up the database thru the Entity Framework. However inorder to prevent sending down EF generated classes across the wire into the proxy generated by the client we have decided to map the values from the EF classes to custom built DTO classes, where the mapper class is responsible for picking out values from the EF generated classes and putting them into the DTO class. We then use those DTO classes for the service method's request and response.
The EF builds classes from tables that are related to each other. I get various classes with properties that look something like these below:
public global::System.Data.Objects.DataClasses.EntityCollection<SubAttachment> Attachments
{}
public global::System.Data.Objects.DataClasses.EntityReference<Gl> GlCodeReference
{}
A few of the properties have the keyword Reference appended to them which I am guessing provides some way for the EF to look up the related table on that field.
Is there a better/different approach than this mapping approach if I dont want to send heavy EF classes across? If not, is there some reference material that will help me understand how the the classes are built by the Entity framework.
Thanks for your time
Since you need to fetch data from WCF service which is backed by EF framework, have you considered using OData to expose EF objects? Check out some links below:
http://www.odata.org/
http://www.hanselman.com/blog/ODataBasicsAtTheAZGroupsDayOfNETWithScottGu.aspx
Link
When you create classes in EF, they have the [DataMember] attributes on their fields, and that's the only data that get's sent accross the wire. So, it's not as heavy as it seems...
But, since you're passing through WCF, the entities should be generated to be self-tracking, so when they get back to the service, you know what's changed and don't have to refetch every entity from db to do comparing.
If you still want the DTO's, you can generate them as well. If you're using EF4.0 you have an option of extracting a T4 file (.tt) that practically does the code generation - use that and alter to suit your needs and generate DTO's as well as mapper classes...
To get a .tt file from edmx (only for EF4): right click your model, choose Add code generation items, and choose EntityObject generator, or the other one if you want to have objects transfered through wcf. This will create a tt file that you can run by issuing a save command (you'll get a prompt if you want to allow it to run). When saved, it will generate a file that's exactly the same as the file generated by edmx model in the case of EntityObject generator, or you'll have two .tt files if you're using the other generator...
I've used something very similar to the approach in the link below along with some custom partial classes and it worked quite nicely.
Link

Categories

Resources