Christian Casutt
Christian Casutt

Reputation: 2423

C# Entity Framework / ASP.NET REST and Models Design Pattern or Solution Architecture

I am developing a .NET 4.0 Windows Service. This Windows service (it must be .NET 4.0) makes a data exchange via REST with an ASP.NET Web API .NET 4.5. The data storage is in a SQL Server. I have decided to make the data access via Entity Framework 6 (.NET 4.5). Now I have a question regarding the model required by the Entity Framework and the .NET Windows Service. If I use Code-First, it works -> i can reference the Model from the Windows Service Project and also from the Entity Framework Project. When I choose database-first, the Entity Framework generates the model classes based on the database and I don't have a dedicated .NET 4.0 assembly with the model classes that i can reference in the .NET 4.0 Windows Service project. I could create an additional .NET 4.0 assembly and define the model classes in there a second time, but this is very tedious and time consuming.

Every square on the following drawing is a separate project. on the second illustration -> the .NET 4.0 Windows Service knows nothing about the model so i can not deserialize the JSON to objects.

i tried to illustrate this

Any hints?

Upvotes: 1

Views: 310

Answers (2)

kuldeep
kuldeep

Reputation: 865

Database entities should not be exposed outside your Data access layer (in this case). You can try to have a separate layer domain/core, where you keep your entities.

A service layer introduction can allow you to have mappings between your DB entities generated by database first, and DTOs that you may want to expose via web API.

The same DTOs should be there on the windows service side too. However, like the comment on OP says, you will have the need to make manual changes in these contracts (DTOs) every time there is a DB migration with new fields added/deleted.

Code first is the way to go just mentioned in other answers/comments !

Upvotes: 3

user10127407
user10127407

Reputation: 108

Code first gives you flexibility to achieve what you want and this is why this is more preferable than DB first.

Code first allows you to have your models wherever you want where DB first will define them with the entity framework context. If you do want to separate them then you will have to put in the extra work recreate them a second time, which is exactly what you want to avoid. There is no other way around this.

Upvotes: 0

Related Questions