5 Rules For DTOs

  Переглядів 32,833

Ardalis

Ardalis

Місяць тому

5 Rules for (better) DTOs
Hey everyone, I'm Steve Smith aka ardalis, of NimblePros!
In this video I'm going to tell you how to write better DTOs using 5 simple rules!
Let me know what you think or share your own tips in the comments below!
Get the Code
You can request the code used in this video here:
mailchi.mp/ardalis.com/5tipsdtos
Links
ardalis.com/dto-or-poco/
ardalis.com/web-api-dto-consi...
Check out my courses:
dometrain.com/course/getting-...
dometrain.com/course/deep-div...
ardalis.com/training-classes/
www.pluralsight.com/authors/s...
Team Consulting and Training: NimblePros.com and @nimblepros
Developer Group Mentoring: devBetter.com
Free Weekly Email Tips:
ardalis.com/tips/
If you read this far, I hope you liked this video and will consider subscribing to my channel!
Find me:
ardalis.com
/ ardalis
github.com/ardalis
/ stevenandrewsmith
bsky.app/profile/ardalis.com
#csharp #dtos #dto #oop #dotnet #visualstudio #webapis #aspnet #aspnetcore

КОМЕНТАРІ: 108
@tomdanielsofficial
@tomdanielsofficial 28 днів тому
Summary: 1) DTOs should not have logic/behavior 1:03 2) DTOs should not enforce encapsulation. They don't need private/protected members. 7:26 3) DTOs should use properties (not fields), otherwise serialization won't work. 8:52 4) DTOs should only use "DTO" in their name as a last resort. Name them for how they are used. 10:13 5) These should be modeled as DTOs: 12:05 - API Request / Reponse objects - MVC ViewModel objects - Database query result objects - Messages (Commands, Events, Queries) * Record types can be helpful for DTOs * MVC models should be DTOs / MVVM models don't * Fluent Validation NuGet Package
@mrwalkan
@mrwalkan 23 дні тому
Thanks
@meetingattender8132
@meetingattender8132 22 дні тому
This comment is better than the video thank you
@Ardalis
@Ardalis 20 днів тому
Thanks!
@pierwszywolnynick
@pierwszywolnynick 16 днів тому
you just saved me 17 minutes
@Ardalis
@Ardalis 16 днів тому
@@pierwszywolnynick What? Check this out: 1. Read this: ardalis.com/5-rules-dtos/ 2. It should save you at most 12 minutes because you can watch at 1.5x speed; 9 minutes if you watch at 2x 😁
@nrjmatta
@nrjmatta 28 днів тому
Always a pleasure listening and watching your videos.
@Ardalis
@Ardalis 20 днів тому
Thanks!
@Robd515
@Robd515 29 днів тому
Awesome quality video and very informative. Looking forward to exploring your videos for your expertise.
@Ardalis
@Ardalis 20 днів тому
Thanks!
@clairelist1060
@clairelist1060 22 дні тому
Your explanation of why we might have a separate DTO for creating a resource vs accessing the resources some other way finally made sense to me!! Thanks!
@johnmaloney7174
@johnmaloney7174 20 днів тому
I wonder why he used createdate as an example though instead of Id. Clearly you need to include Id (that wouldn't exist in the requestDto) in a responseDto.
@Ardalis
@Ardalis 20 днів тому
@@johnmaloney7174 Yes that's often true, too, especially for database-generated keys! There was no particular reason why I went with CreateDate aside from the fact that you basically never want some client to send that to your backend (rather than you controlling it) while in some cases you may be OK with client-generated keys (like with GUID keys).
@fernandocalmet
@fernandocalmet 29 днів тому
Great video, Steve. Thank you for sharing
@Ardalis
@Ardalis 29 днів тому
Thanks!
@m4rc0k1tt3L
@m4rc0k1tt3L 29 днів тому
Thank you for this Video. I really love c# as a programming language. For me it is the most complete one.
@Ardalis
@Ardalis 29 днів тому
You’re welcome and I love it as well.
@touabdelhak
@touabdelhak 17 днів тому
Thanks for the content!
@Ardalis
@Ardalis 16 днів тому
My pleasure!
@grzegorzborowski4284
@grzegorzborowski4284 2 дні тому
Great stuff. Would be nice to see more of your publicity.
@vadimemelin2941
@vadimemelin2941 24 дні тому
Just what I was looking for! Cheers!
@Ardalis
@Ardalis 20 днів тому
Thanks!
@VishalTrivediB
@VishalTrivediB 25 днів тому
Great tips, thank you very much!
@Ardalis
@Ardalis 20 днів тому
Glad it was helpful!
@mumk
@mumk 29 днів тому
thanks for sharing!
@Ardalis
@Ardalis 29 днів тому
You're welcome!
@OzgulEzgin
@OzgulEzgin 29 днів тому
Thanks for the video Steve. May be you do a video on best practices for mapping dto's as well. Looking forward to it. Best regards.
@Ardalis
@Ardalis 29 днів тому
Great suggestion!
@theyuribanker
@theyuribanker 26 днів тому
I need!!!
@caseyspaulding
@caseyspaulding 15 днів тому
Great stuff. Thanks
@Ardalis
@Ardalis 8 днів тому
Glad you enjoyed it
@TammamKoujan
@TammamKoujan 29 днів тому
Nice and clear video; I hoped that it talked about DTO mapping since it is an essential topic
@Ardalis
@Ardalis 29 днів тому
Thanks, I’ll try to cover that (and the fact that you can certainly have static helpers on your DTO types without breaking any of the rules) in a future video
@TammamKoujan
@TammamKoujan 26 днів тому
@@Ardalis , what I meant is that mapping is an essential topic for DTOs, and it would be a good addition to this video since people are using different approaches. Some use mapping libraries like AutoMapper, even though this is not widely recommended nowadays, while others do it manually. Personally, I use a combination of extension methods and Func Delegate with Expression.
@MrSupasonik
@MrSupasonik 24 дні тому
@@TammamKoujan I for one support the approach with extension methods, but could you elaborate please how do you use Func Delegates with Expressions?
@DebugModeVideos
@DebugModeVideos 26 днів тому
Thanks Steve
@Ardalis
@Ardalis 20 днів тому
You're welcome DJ!
@codefoxtrot
@codefoxtrot 29 днів тому
Very rich content for a video that could have easily been a mid-level course! Thanks Ardalis!
@Ardalis
@Ardalis 20 днів тому
Glad you liked it!
@AndreNunes-ps5mc
@AndreNunes-ps5mc 23 дні тому
great content!
@Ardalis
@Ardalis 20 днів тому
Thanks!
@privatesocialhandle
@privatesocialhandle 11 днів тому
No idea why some people are lemon. Thanks for taking the time to provide the knowledge.
@Ardalis
@Ardalis 8 днів тому
Thanks for watching!
@theyuribanker
@theyuribanker 26 днів тому
Thanks for sharing this rich content. I have a question about Repositroy. Do you intend to implement Unit Of Work pattern in Ardalis.Specification? or is it not good?
@Ardalis
@Ardalis 20 днів тому
On Specifications, no. On the Repository we ship in Ardalis.Specification package? I don't intend to do so but others can (and have). Honestly that Repository implementation is a bit of a monster because I've accepted just about every pull request from folks wanting "just one more" method on it, so it's no longer as tightly designed as I would prefer. Some day if I have time I may create an Ardalis.Repository that looks to fix this, but for now I have been living with the monster (and only using the bits I need) or just implementing a custom version in my customer's apps (which basically just means copying the base repository class and removing all the things they don't need).
@alfonsdeda8912
@alfonsdeda8912 29 днів тому
Nice video! So if I have an entity that have some behavior with create method and validation in it is better to create a separate dto and a separate validator for this entity or is okay to use directly the entity if the behavior regards only the validation inside it self?
@Ardalis
@Ardalis 29 днів тому
If you’re creating the entity via some user input via an API or form Post, use a DTO for the over-the-wire data. Validate it and let the user know if they need to fix anything. Then call the Create method and pass it the parameters it needs from the DTO’s properties.
@alfonsdeda8912
@alfonsdeda8912 29 днів тому
@@Ardalis Is good to create an dto and populate from user form and pass directly to create method after validation instead of creating two separate classes?
@joshuawillis7874
@joshuawillis7874 16 днів тому
Good video! I'm kinda curious - do you think properties are considered more first-class for C# because of their syntactical sugar options (auto-props, get-only, init-only, etc.), or more for the original reason that they lowered into the common getter/setter pattern and regression, or is there another reason? It feels like the main reason to me is regression for getter/setter.
@Ardalis
@Ardalis 16 днів тому
All of the above? The language team keeps improving them. Tools and libraries typically work with them out of the box, by default, without additional configuration or hacks. Having proper property support was always one of the things that distinguished C# from Java (some more info here: stackoverflow.com/a/3430218/13729).
@evildoer1606
@evildoer1606 26 днів тому
What do you think about using record structs as DTOs? Seen it in some codebases. What are the pros and cons?
@Ardalis
@Ardalis 20 днів тому
I think record struct is basically an improved version of struct, and you should use it in 99% of the places where you might otherwise use a struct. Now, as to whether you should use a struct for your DTO types, I think this Stack Overflow question summarizes most of the use cases, and (TL;DR) recommends sticking with classes for most DTO use cases. stackoverflow.com/questions/11014501/dto-classes-vs-struct
@AlwaysHCYT2
@AlwaysHCYT2 26 днів тому
Attributes in record fields need "property:". In your example: [property:EmailAddress] string Email
@Ardalis
@Ardalis 20 днів тому
Yep, someone else mentioned that as well. Thanks!
@johnmaloney7174
@johnmaloney7174 20 днів тому
I would also suggest that your Data Access Layer only returns DTOs - that is, when using EF or EF with a Repo layer, that the DAL/Repo accepts and returns DTOs to/from the App layer. This way the app is clearly decoupled from entities/persistence & any business logic works exclusively with business models (dtos) . Both App & DAL would hold a reference to the Model project, but the App would not hold a reference to the DAL. Repo interfaces would be defined in the Model project but implemented in the DAL project.
@Ardalis
@Ardalis 20 днів тому
Repository is a DDD pattern. It's meant to work with the Domain Model, which includes your Entities and Aggregates. Those are the types it should accept/return, not DTOs. DTOs are typically an Application concern, and are used for ViewModels and API messages, etc. The only DTOs I typically have in my domain model are domain events. For simple apps you can just have your Web/UI layer use repositories, work with the domain model, and do whatever mapping is needed to DTOs. But for more complex apps (like ones that typically require DDD) I am typically using a UseCases project as my Application layer which does all the work of talking to the domain model and mapping DTOs. Then the web layer simply sends messages to the UseCases layer and gets back results with DTOs that are ready for it to use. See my Clean Architecture template on GitHub as an example.
@dallyoluwafemi2827
@dallyoluwafemi2827 Місяць тому
did you build the ardalis nugets?
@Ardalis
@Ardalis Місяць тому
do you mean did I author them? yes, that's me.
@bensadik
@bensadik Місяць тому
I do the same thing, but I add mapping methods: record CreateItemRequest(string Name, string Value) { public Item ToEntity => new Item(Name, Value); }
@TammamKoujan
@TammamKoujan 29 днів тому
In this way, your DTO is doing more than just transferring data (Single Responsibility Principle); with more complex mapping scenarios, you will end up with a DTO that does many things out of its scope, is less flexible, and is less maintainable. Also, you are adding a dependency on your entity classes and tightly coupling them.
@henriquesouza5109
@henriquesouza5109 29 днів тому
@@TammamKoujan Yeah, that's like putting the entity construction logic in the request object rather than in the entity constructor (where it should be in the first place). I prefer naming them "Input/Parameters" rather than Request/Dto etc since Request is usually bound to http domain and Dto doesn't mean anything at all. If you have a constructor "Item(string name, string value)" and you wanna expose this interface to the http (remember http is just a layer on top of your application), then what happens is you create a class to wrap exactly "name" and "value" function parameters, so why don't you name it so? CreateItem is the function, and name + value are the parameters, therefore CreateItemParameters, CreateItemParams or CreateItemInput (in Input/Output pov).
@Ardalis
@Ardalis 29 днів тому
Adding static helpers to map to/from other types is fine IMO. Extension methods probably even better, though. Avoid instance methods since those break first rule and introduce issues others are commenting on.
@bensadik
@bensadik 29 днів тому
@@Ardalis extension methods are a great idea for this particular purpose, but it’s only a C# thing, for other languages this is just fine IMO
@Ardalis
@Ardalis 16 днів тому
Article version: ardalis.com/5-rules-dtos/
@maciejwawoczny1174
@maciejwawoczny1174 5 днів тому
If my API return "UserResponse" which contain other class inside, how to name that inner class? class UserResponse { public InnerClassResponse/InnerClassDTO/InnerClass? } Same example with Requests etc
@Ardalis
@Ardalis 3 дні тому
Something like this: class CreateUserResponse { public UserDto User {get; set;} // other properties, metadata if needed } In some cases it might make sense to have a standard Response structure in which case the resulting data might always go into a "Payload" or "Result" property, which might be of type object or string.
@scotmcpherson
@scotmcpherson День тому
These rules although great for abstraction, have an impact of runtime efficiency. When a server is dealing with lots of lots of concurrent realtime data streams, this can have a negative impact.
@Ardalis
@Ardalis 12 годин тому
Which?
@scotmcpherson
@scotmcpherson 10 годин тому
@@Ardalis Have you ever looked at runtime optimized code? It's not organized, and can be hard to read. Prototyping with organization is important, but once you go into release, if it needs every sliver of performance, then your organization gets torn to shreds.
@vasant2411
@vasant2411 28 днів тому
How should we name response object return from command
@Ardalis
@Ardalis 24 дні тому
CommandNameResponse probably
@JjKoller85
@JjKoller85 29 днів тому
What is your take on inheritance on DTOs (especially Request and Response of WebAPIs)? I've seen it quite often in the past years. Following your first rule, I would assume that we rather should duplicate properties on DTOs?
@ddrsdiego
@ddrsdiego 29 днів тому
This is a really good question and given my years of experience in integrations I can say that starting with inheritance seemed to make sense but over time each endpoint starts to gain more life and management starts to become complex due to inheritance. What has worked for me is maintaining a canonical model and sharing it with all areas and yes, repeating properties in Requests and Responses
@Ardalis
@Ardalis 29 днів тому
I used to use inheritance for instance between a Create and an Update DTO I might have Update inherit from Create and just add an Id property (since db-generated Id wouldn’t be on a Create record). But it often turns out that’s not where the differences end and these days I just keep the types separate so there is no coupling between them. The duplication hasn’t caused me any troubles yet.
@mmuekk
@mmuekk 27 днів тому
I use interfaces instead inheritance
@jackeinstein2184
@jackeinstein2184 21 день тому
@@mmuekk could you please explain how?
@keesdewit1982
@keesdewit1982 29 днів тому
Rocky Balboa teaching me about DTOs. I love it 😅
@Ardalis
@Ardalis 29 днів тому
Heh, used to be folks thought I looked like Alec Baldwin from 30 Rock. Now with long hair I guess I'm Rocky... I'll take it. :)
@keesdewit1982
@keesdewit1982 29 днів тому
@@Ardalis You are just a nice guy ;) Thanks for providing these videos.
@AlFasGD
@AlFasGD 29 днів тому
I strongly disagree with the point about using properties over fields. Properties are very cumbersome to write, and fields are straight-foward. You can setup your serializer of your choice (Newtonsoft, System.Text, or any other) to also discover the fields in your DTO. The only drawback that fields have is that they do not implement interfaces, and in the case that your DTO implements one, you have to stick to properties. Speaking of interfaces, you did not touch the subject of having all those common fields like ID, email, first and last names, etc. Oftentimes you are mapping them out individually, having more boilerplate code for passing all that information around, than actually using and processing it. Sometimes, it might come in handy to use interfaces to abstract away that responsibility of mapping objects like this, and allow for multiple objects to be mapped out via their interface properties.
@spacemanjack777
@spacemanjack777 27 днів тому
Writing properties is cumbersome... really? But a custom serializer configuration instead of ordinary properties and be done with it? Yes, properties takes a few more characters to type than fields, but most of the time nobody is actually typing in those are they? I mean, code intellisense.
@AlFasGD
@AlFasGD 27 днів тому
@@spacemanjack777 whatever you do to make your property declaration process shorter, it's still longer than fields. That's all.
@Ardalis
@Ardalis 20 днів тому
Properties are trivial to write these days and almost always auto-completed by your IDE or else easily copy/pasted when you're creating several of them. Leveraging the default behavior of the framework instead of requiring customization is way more valuable than trying to save a few characters on declaring your class members, IMO. But if it's working for you, go for it.
@anomalii7720
@anomalii7720 26 днів тому
But, for the record, it's your 5 rules. And that doesn't mean anything. 🙂
@chudchadanstud
@chudchadanstud 26 днів тому
🙃
@Ardalis
@Ardalis 20 днів тому
What did you expect it to mean? All rules are made up by someone.
@privatesocialhandle
@privatesocialhandle 11 днів тому
You're constructive.
@wandie87
@wandie87 21 день тому
Great video. I typically end up with multiple DTOs (Whether these are Request or Response types) for specific use cases. For example: UserResponse.cs UserWithAddressResponse.cs UserWithBirthdateResponse.cs Each response would be used for a different API request to ensure I am only sending the required information back over the wire (no oversharing). Is this problematic? If so, how would be best to improve upon this? I feel I end up with a lot of replicated code... Thanks
@Ardalis
@Ardalis 20 днів тому
I'm with you. I'd rather have independent DTOs for different API endpoints with a bit of duplication between them but no coupling than have some inheritance hierarchy that might bite me later with an unforeseen consequence of sharing. I've been building APIs for a LONG time and my trend has been toward increasingly independent endpoints. In the beginning, like most .NET devs of the time, I had big controllers with big DTOs and minimal duplication (DRY all the things!) but now I use API Endpoints (usually fast-endpoints.com) with bespoke Request and Response DTOs for each endpoint (REPR Pattern) and I've found this makes it MUCH easier to build and modify individual endpoints without risk of breaking others.
@wandie87
@wandie87 20 днів тому
@@Ardalis I agree. How do you deal with nested DTOs? Take my UserWithAddressResponse.cs example above. Do you have a child DTO for address that you reference or do you do it all in the single top level DTO? If the child reference route, is this shared between other DTOs or bespoke to the user object?
@Ardalis
@Ardalis 20 днів тому
@@wandie87 Probably an AddressDTO with the basics, and an array of them for the UserWithAddress (assuming they have more than one) or just a property if only the one. I've never really thought about my personal "rules" for such things but thinking about it now I tend to create very simple "FooDTO" types for "leaf node" objects that have no references to other objects (especially collections). These will usually live in my UseCases/Application layer since that layer is usually responsible for returning them to the UI layer in response to queries/commands/messages sent to it. The leaf node DTOs are (somewhat) reusable, and may be (re)used to compose more custom Request/Response etc DTOs. The more complex DTOs (like UserWithAddress for instance) are usually less reusable and more customized to a particular operation.
@wandie87
@wandie87 20 днів тому
@@Ardalis I’d never put much thought into it either until I watched your video. Triggered me to have a think about how I structure this stuff going forward and augment some of my own rules into the ones you provided.
@doubleMSW
@doubleMSW 29 днів тому
If you're using EF Core and reference the id from one "DTO" to another (i.e. OrderDTO, OrderItemDTO, ProductDTO) in EF Core I've aways seen a reference in the DTO: public class OrderDTO { public Guid Id { get; init; } public string OrderNumber { get; init; } ... // If you had a many to many there would be reference to a collection from a link entity // If you had a one to many there would be a reference to a collection of the many side (i.e. OrderDTO and OrderItemDTO which linked to a ProductDTO) } public class OrderLineItemDTO { public Guid Id { get; init; } public Guid OrderId { get; init; } public int ItemNumber { get; init; } ... public OrderDTO Order { get; set; } public ICollection LinkOrderItemProductCollection { get; set; } } I don't want to continue down the rabbit hole here, hopefully you get the jest of what I'm referring too... Thoughts???
@Ardalis
@Ardalis 29 днів тому
EF Core shouldn’t be working with DTOs directly - I assume you’re talking about mapping entities to DTOs, right?
@doubleMSW
@doubleMSW 29 днів тому
@@Ardalis correct
@johnmaloney7174
@johnmaloney7174 20 днів тому
It's a good question, but the navigation properties that exist on entity object don't need to exist on the dto. If you use Automapper, it will populate those properties with the related objects/object collections without hassle.
@Ardalis
@Ardalis 20 днів тому
@@johnmaloney7174 Exactly. Sometimes you'll want the related objects in the DTO structure, sometimes you might just want the IDs. For instance when getting a collection of Orders from a GET /orders endpoint you might only get the top level order info, but then if you GET /orders/123 you will often get additional information including the details of the line items. The "shape" of your DTO data will often vary with context, and won't often correspond directly to your domain entity or data model.
@mesutdemirci7933
@mesutdemirci7933 22 дні тому
Great tips, thank you very much!
@Ardalis
@Ardalis 20 днів тому
You're welcome!
REPR and Clean Architecture
11:48
Ardalis
Переглядів 12 тис.
Этого От Него Никто Не Ожидал 😂
00:19
Глеб Рандалайнен
Переглядів 5 млн
Teenagers Show Kindness by Repairing Grandmother's Old Fence #shorts
00:37
Fabiosa Best Lifehacks
Переглядів 6 млн
The 3 Biggest Mistakes of Object Mapping in .NET
11:33
Nick Chapsas
Переглядів 62 тис.
5 Signs of an Inexperienced Self-Taught Developer (and how to fix)
8:40
Travis Media
Переглядів 464 тис.
Avoid Deadlocks
4:10
Jeff Zuerlein
Переглядів 1,3 тис.
How IEnumerable can kill your performance in C#
11:02
Nick Chapsas
Переглядів 110 тис.
If this ships, it will change javascript forever
25:54
Theo - t3․gg
Переглядів 179 тис.
The Best Software Engineering Advice | Prime Reacts
55:05
ThePrimeTime
Переглядів 238 тис.
Make Your LINQ Up to 10x Faster!
11:08
Nick Chapsas
Переглядів 51 тис.
Why I Quit Copilot | Prime Reacts
35:56
ThePrimeTime
Переглядів 235 тис.
X86 Needs To Die
1:09:15
ThePrimeTime
Переглядів 315 тис.
Await Async Tasks Are Getting Awesome in .NET 9!
9:24
Nick Chapsas
Переглядів 79 тис.
Why spend $10.000 on a flashlight when these are $200🗿
0:12
NIGHTOPERATOR
Переглядів 16 млн
Крутое обновление microReader!
5:54
Заметки Ардуинщика
Переглядів 24 тис.