Understanding Entity Framework classes - c#

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

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.

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

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.

Entity data inheritance

I'm currently involved in a project where we will present data from an external data source to visitors, but we will also provide meta data for the entities/rewrite some of the original data.
The external data source is a SQL Server database which I've created an .edmx file from and I've created an additional, controllable, SQL Server database with it's own .edmx file. But I'm not comfortable with using two entities for what, in my eyes, is one type of data.
Somehow I would like to merge the two data sources into one, and use only one entity class which I could query. Inheritance in LINQ to Entities would be perfect, but I would prefer no to change the .edmx files manually.
As it is now I have to create wrapper classes and populate them manually with the entity classes, or use multiple database queries to fetch the required data which is a big turn off performance wise.
It feels like it have to exist some sort of work around for these problems I'm facing?
You have two options here.
First you can extend the entity framework class by using partial
classes. It will help you avoiding changes to the generated classes.
Second you can use Entity Framework code first, Which i will
recommend as you will have more control on your entities.

Categories

Resources