Blazor WASM with EF Core: Where to put data model code?

Viewed 771

When using Blazor WebAssembly, be default, three projects are created - Client, Server and Shared. Which project is the best choice for code which defines EF Core data model?

  • If I put it in Server, I have to create it's client counterpart in the Client project, which creates redundant code
  • If I put it in Shared and use Data Annotations, the client becomes transitively dependent on EF Core
  • If I put it in Shared and use Fluent API, I'll have to check multiple files to understand even a single property (e.g. is this property required? what is it's max length?)

It seems like I'm picking the lesser of three evils, which seems to be the Fluent API. Are there any other aspects that I didn't consider?

2 Answers

You put DTOs (Data Tranfer Objects) in the Shared project. That is one of the key benefits of Blazor.

You can use your Model Entities as DTOs but I would only consider that for (very) small projects. And then EF (DbContext and Fluent API) is still only needed on the Server. Don't add it to the Shared project.

For larger projects, use separate DTOs and do the mapping in the Server APIs.

Use attributes from the System.ComponentModel.DataAnnotations namespace on the entities in the Shared project. These are useful in the UI and for client-side validation and will not introduce a dependency on EF.

Then use the fluent API in the Server project for any additional EF configuration.

Related