C
C#4w ago
joopy

DTOs - I'm so lost its unreal

So I had a good conversation last night about DTOs and thought I understood it. Now I'm more confused than ever. I'm building a game server in C# and its turned into a project nightmare spanning many class libraries and nuget packages. I'm trying to consolidate some of that via using dtos to avoid exposing EF entities but come across an issue. If my .API project references (and hosts) dtos instead of ef entities, that means my concrete classes (the classes implementing .API's interfaces) must also accept the dtos into methods, as fields, etc, obey the contract Current setup is... App.Db (nuget package; only cuz .API references entities right now) - holds db context and ef core entities, migrations, db stuff App.API (class library, nuget package) - plugin devs install this nuget package to write plugins AppServer (main runtime, console application) - concrete classes to .API's interfaces So I decided, instead of .API using .Db's ef entities, and causing .Db to also be a nuget package, use dtos... Now the problem is, if my AppServer concrete classes have to reference Dto, if my dto has less data (not exposing certain bits to plugin devs) than the entity, mapping to and from will cause irrecoverable data loss? I'm aware I've got something very very wrong here and I am appealing to the members of this server to set me straight. Thanks so much.
3 Replies
Jimmacle
Jimmacle4w ago
your DTOs should contain all the information necessary to send between the two systems that are communicating DTOs are simply classes where the sole purpose is defining what data is exchanged between a client/server, caller/callee, etc.
joopy
joopyOP4w ago
Okay so the solution is just to make them 1:1 ? If I need to hide data from plugin developers, would that need an extra layer? Thanks for the reply btw.
Jimmacle
Jimmacle4w ago
the solution is to make the DTOs contain the data needed by whatever is receiving them, however that ends up looking if you need to hide data from the receiver, don't put it in the DTO probably won't be 1:1 with your EF entities because that's the reason not to leak them in the first place, EF entities will have EF specific things like navigation properties, keys, etc. that don't make sense or aren't necessary outside of working with the database i have DTOs that are relatively complex projections built from data from multiple db tables, it depends entirely on what "shape" of data you want the thing consuming the api/service/etc to work with

Did you find this page helpful?