Pharylon
Pharylon

Reputation: 9916

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:

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?

Upvotes: 1

Views: 370

Answers (3)

Gert Arnold
Gert Arnold

Reputation: 109079

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.

Upvotes: 2

Ric .Net
Ric .Net

Reputation: 5540

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

Upvotes: 1

sfuqua
sfuqua

Reputation: 5853

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.

Upvotes: 1

Related Questions