Use Data Transfer Objects (DTOs) in .NET the Right Way 🚀

Поделиться
HTML-код
  • Опубликовано: 25 янв 2025

Комментарии • 69

  • @r.osorio02
    @r.osorio02 3 месяца назад +4

    It’s a good practice, I believe. After being using AutoMapper for years I ended up doing a small class to write my mappings without an external library. Either way, with libraries or any other approaches, the main goal is seizing the benefits from the DTO. More code but cleaner code. We normally have to write that code once and that is barely touched again.

  • @nlisimalaba6094
    @nlisimalaba6094 3 месяца назад +2

    Simple and straight forward. Have never used Mapster though for mapping, will try it out.

  • @dasfahrer8187
    @dasfahrer8187 3 месяца назад +7

    DTO's also great for when you need to add annotations to properties since those probably shouldn't be added directly to the data model (especially in EF if you're doing db-first and need to regenerate them due to changes).

    • @temp50
      @temp50 25 дней назад

      Except, do not add properties to a 'POCO' class. If you need input model validation do it somewhere else.

    • @dasfahrer8187
      @dasfahrer8187 25 дней назад

      @@temp50 Eh, without getting too far into the semantic weeds, DTO's are POCO's, which is where annotations typically live. So it's fine. There are multiple ways to skin the validation cat, all which are perfectly valid in a given context, so you should probably expand upon what mean.

  • @yumyum7196
    @yumyum7196 3 месяца назад +6

    I haven’t used Mapster. I usually add a constructor to the DTO that takes a model.

    • @mdiqbalhossain8844
      @mdiqbalhossain8844 3 месяца назад +1

      Could you please give us a example code.

    • @r.osorio02
      @r.osorio02 3 месяца назад

      @@mdiqbalhossain8844let’s say: public GameCharacterResponse (GameCharacter source) { return new GameCharacterResponse { Name = source.Name, (same for other props)};}

  • @mtranchi
    @mtranchi 3 месяца назад +6

    Since Blazor, I'm done with DTO's. I put my Entity models right in the client project. 99% of Entities are pretty much known, like an order and order items. Just makes the code easier, faster to build.
    If there's something I don't want to expose to the user, I'll slap a [JsonIgnore] attribute on it. Yes, the end user could decompile the WASM and see the fields, but there'd be no "hidden" data.
    On the rare occasion I really do need to keep sensitive data from even hitting the browser in any way/shape/fashion or form, then yes, I'll put that entity in the server and use a DTO.
    and if you're gonna use a mapper, like others in the comments are saying, Mapperly all day, ALL DAY! Quick, easy, and runs at build time, so no overhead startup.

    • @petropzqi
      @petropzqi 3 месяца назад

      Interesting take. You don't feel it getting a bit cluttered? I mean if you have audit values like created at updated at etc...

    • @mtranchi
      @mtranchi 3 месяца назад +2

      @@petropzqi Reckon it depends on your app. I'm in the process of building a custom blogging engine, so 'created at updated at' is part of the model you want to send down to the browser to display to the user.
      me, i feel like it's cleaner, ESPECIALLY during development--there's no having to maintain the Entity as well as the DTO as you flesh out your vision.
      and any fields that are part of... say, clicking a checkbox to mark several Entities in a list for deletion, I just put a "Deleting" property on the entity and throw a [NotMapped] attribute on it so that when the user hits "Delete", i can cull them and send them to the server to be deleted.
      when i create an Entity, i have three #regions: Keys, Properties, and UI/Not Mapped/Getters. Getters are like, the total for an order where it sums the line totals for each order item.
      not sure how efficient this is because Entities from the database and from JSON, these properties need to be hydrated, as well as written to JSON when posting to the server. But if it's a fairly small-time website, I haven't noticed any appreciable tax on resources on my servers.
      and... again, i'm usually not writing mission critical code like NASA:
      ruclips.net/video/GWYhtksrmhE/видео.html
      and if you're handling sensitive data like credit cards or medical records, that's a whole different animal... sorta.
      i mean, any hacker out there is gonna know the fields one needs for a valid credit card, so does it really matter if you send down a DTO? For the user to fill it out, it's gonna have all those exact same fields, so what does a DTO get you from a security perspective? I guess you could name the properties a bit different in the DTO (security through obfuscation), but one should prolly put their efforts into making sure no one gets root access to the site and not find your connection string.
      every site i build i make a role that's just for me (call it "God" mode in honor of Patrick, lol), but even me, i don't get root access to all the data (mostly just access to logging so i can see what's going on). Admin gets the access they need, but even then, they get double-checked on who they are and what they're allowed to do on the server before i let them make a move, which...
      we're getting deep into the weeds here, but another thing to protect against is a user to be able to go through your data by an integer or long id in the url. Always use Guids for more sensitive data, and never expose them in the url.
      overall, always think that most humans are kind and decent people, but there's some real shit-stains out there, and... "How can a shit-stain wreck my day?"

    • @fifty-plus
      @fifty-plus 3 месяца назад

      Yes, the entire point of layer models is to remove coupling. I'd recommend at least a response (or consumed) object different to your lower layer objects so you can absorb any lower changes within the mapping and having at least a 2-tier then 3-tier+ as the size requires it.

    • @temp50
      @temp50 25 дней назад

      It is against things like layered architecture since you are most probably violating the concept of context boundaries> Your service code is the only place where you should use both model classes and DTOs at the same time. The input and the output should always be a data-model-independent type. Moreover, the input must always be treated as a potential attack against your service so never 1:1 map it to your datastore.

  • @temp50
    @temp50 25 дней назад

    5:43 As a note here: The majority of the industry is now _against_ using any kind of mapper library simply because
    - the mapper logic is easy to write
    - you can get rid of a 3rd party dependency
    - you will have full control of not just the mapper logic, but its performance also.

  • @joaogabrielv.m328
    @joaogabrielv.m328 3 месяца назад +3

    Really would like a video about Mapperly. It's a source generator, even faster then Maspter and easy as well

  • @JayTandon-nq9du
    @JayTandon-nq9du 3 месяца назад +4

    Mapperly is a very good mapper ... uses source generators

  • @SlimBenRomdhane-u4g
    @SlimBenRomdhane-u4g 3 дня назад +1

    Great video thanks. I have a question tho, what's the difference between dto and viewmodel if possible an exemple thanks.

    • @aymanelrw
      @aymanelrw 3 дня назад

      The ViewModel is designed for the view/UI layer and may contain UI logic for state management meanwhile the DTO is designed for data transport between systems (frontend and backend) and contains no logic which makes it purely a data container.

  • @afshin7104
    @afshin7104 3 месяца назад

    I think the best use case of DTO at least in my projects is projection when you can select exactly what you need from data base instead of select *

  • @AliyProgrammer
    @AliyProgrammer 3 месяца назад +3

    I use Auto Mapper extension what difference between Auto Mapper and Mapster? Thanks for your answer

    • @AtikBayraktar
      @AtikBayraktar 3 месяца назад

      automapper is also good and comprehensive, but mapster is really easy and fun to use as it states. my go-to mapper everyday.

    • @fusedqyou
      @fusedqyou 3 месяца назад +3

      Mapperly doesn't use reflection but source generation. This makes it very fast and removes the requirement for reflection. However, still not as fast as just doing it manually, which is also a lot more controllable.

    • @AtikBayraktar
      @AtikBayraktar 3 месяца назад

      @@fusedqyou yes i forgot that!

  • @LinkingTheWorlds
    @LinkingTheWorlds 3 месяца назад

    May i suggest to have DTO as sealed record, instead of class.

  • @_miranHorvat
    @_miranHorvat 3 месяца назад

    At the monent my DTOs are still WCF Contracts. :-) In a pilot project I went the "gRPC First" route. I still have hopes for gRPC to WCF trancoding.

  • @mohammedsaqlainshaikh7029
    @mohammedsaqlainshaikh7029 3 месяца назад

    Really Great Explaination but are you looking for a video editor?

  • @nieuwveen
    @nieuwveen 3 месяца назад

    Nice, but this will stil load all the data from the database?

  • @ArmandoPineda4
    @ArmandoPineda4 3 месяца назад +1

    You're the best!!

  • @HaeriStudios
    @HaeriStudios 2 месяца назад

    Great video! Is there any chance you could make a tutorial on how to best set up projection code for DTOs? I haven't found a good way to write reusable projections because it either needs to happen in memory after pulling full objects from the database, or I have to write the mappings by hand every single time I do a select to get good performance. But that is really cumbersome especially with DTOs that have multiple levels of data (which are also DTOs)

  • @camrws
    @camrws 3 месяца назад

    wait i didn’t know with mapster you don’t have to explicitly define the maps you make in a mapper class like in automapper… actually might check out mapster for this reason lol

  • @STech_Videos
    @STech_Videos 3 месяца назад

    How may i get connected with you for video editing process?

  • @Rick-mf3gh
    @Rick-mf3gh 3 месяца назад +5

    I am with Nick Chapsas on auto mappers: don't use them. Your code will happily compile and run even when the auto mapping is broken.

    • @kristiadhy
      @kristiadhy 3 месяца назад

      what is the drawbacks of using AutoMapper?

    • @kristiadhy
      @kristiadhy 3 месяца назад

      @@gppsoftware so what is the better option then?

    • @kristiadhy
      @kristiadhy 3 месяца назад

      @@gppsoftware I see, thank you

    • @Rick-mf3gh
      @Rick-mf3gh 3 месяца назад

      @@kristiadhy One of the worse drawbacks is if you have 2 objects that are correctly mapping and then you add a new property to one of them, your code will happily compile and run, even though it is technically broken. You can get this issue without automapper, but it is worse with it.

    • @FBender
      @FBender 3 месяца назад

      @@kristiadhy You can also use source generators. In that case you will also handle situations with varying dtos.

  • @EgorUshakov
    @EgorUshakov 3 месяца назад

    1:28 You said that DTO transfers data between layers of your application. What are the layers between which DTO in your example transfers data?

    • @AFPinerosG
      @AFPinerosG 2 месяца назад

      It's an example

    • @aymanelrw
      @aymanelrw 3 дня назад

      In case of mobile or desktop app i guess because you have business logic (Controller,Presnter or Viewmodel...) with UI in the same project.

  • @adam-xt8te
    @adam-xt8te 3 месяца назад

    Entity -> DTO -(cloud)-> (what here?) -> Model in MVC/MVVM
    Where on client side DTO should be mapped to other object, immediately?

  • @llanesluis19
    @llanesluis19 3 месяца назад

    Do I need a DTO if my Entities have to recurve extra fields in order for EntityFramework to pick up and make the right relations?
    Like I have an Entity that needs only 3 fields but when I read it from a GET request I get like other 3 fields set to null, when I try to .Include() it says it’s doing an infinite cycle. :(

  • @aymenbachiri-yh2hd
    @aymenbachiri-yh2hd 3 месяца назад +1

    Thanks you so much

  • @uk-yy4qb
    @uk-yy4qb День назад +1

    Cool

  • @AthelstanEngland
    @AthelstanEngland 3 месяца назад

    Thanks. You mention combining data from different models in a DTO but then don't show that. That is the bit I would really like to see if anyone has any pointers.

  • @sumanshah5750
    @sumanshah5750 3 месяца назад

    You really make t simple..... Can you make angular and. Net mvc or web api..... From scratch which is demanding now days

  • @Hasan10-oh7vl
    @Hasan10-oh7vl 3 месяца назад

    Love itt !!
    You need a video editor bro ?
    I can do a sample vid :)

  • @bauminator610
    @bauminator610 3 месяца назад

    Hello, by the Way very good Video. My Question ist if i have an DTO without the ID Column how can i make the Update to the Database. Example: GameCharacter with ID Column and GameCharacterResponse without. Select into DTO is clear but when i update the DTO Changing the Name und Safe it to the Database i Need the ID to Update the Record in Database or am i Wrong? Thanks fpr the help :)

    • @krccmsitp2884
      @krccmsitp2884 3 месяца назад

      The ID should always be part of the endpoint route, like so: PUT /api/customer/1234

    • @bauminator610
      @bauminator610 3 месяца назад

      @@krccmsitp2884 Thanks for your answer. This is right when i get the Customer Object map it to DTO without IDthen i had no id in my Frontend to put in the URL . For Example a List of DTOs. Hope this is understandable.

  • @ThatDeveloperDad
    @ThatDeveloperDad 3 месяца назад

    I like this, but I tend to avoid AutoMapper for translations. Each component in my system will have classes that describes the BusinessEntity upon which they act. The Presentation component may look significantly different from the Logic component, which also looks different from the Storage component's view of that one Entity. Those representations form the DTOs exposed by a Dependency.
    Storage Access exposes the PUBLIC idiomatic form of the Storage Model (never expose the actual Storage Model. It will taste like regret.)
    The Logic components expose the Public idiomatic form of the Business Model, and are aware of the ResourceAccess idioms. They translate that Business Model to and From the Storage Model as needed.
    Presentation have their own representations of the Entity, and are aware of the Business Models exposed by the Logic Components on which they depend.
    Additionally, we may have significant differences in these objects from one Process or Activity context to the next. (Vertical Slice thinking here...)
    .Net Extension Methods are almost always sufficient for this purpose, and more importantly, enforce the conceptual isolation between the components in my system. I've found that AutoMapper causes leakage between layers, as it can allow pollution across the contextual boundaries of the system. (A Customer can look wildly different to the Marketing use cases than it does for the Finance use cases, etc...)
    Great explanation though.

  • @krccmsitp2884
    @krccmsitp2884 3 месяца назад

    I'm picking "R" and wanna solve ;-)

  • @mr-black_rock321
    @mr-black_rock321 Месяц назад

    Why every developer using setter in DTO

    • @temp50
      @temp50 25 дней назад

      TL;DR: "prop"

  • @fusedqyou
    @fusedqyou 3 месяца назад +1

    Using a mapper just introduces bloat. Introduce a static method on your DTO that creates an instance based of your object and use that instead. This avoids having to have a mapper, and it takes no more than half a minute to write the code. Easy reusable static method that can be modified to possibly introduce more complexity that mappers can't have (varied data, dynamic data).

    • @krccmsitp2884
      @krccmsitp2884 3 месяца назад

      How do you ensure all properties are thoroughly mapped, esp. when you add a property in the future? Mapster generates the mapping code, without runtime reflection you can debug it, step through it.

    • @fusedqyou
      @fusedqyou 3 месяца назад

      @@krccmsitp2884 This is why the static method is used. If you add/remove data, then the static method inside the class is updated.

    • @temp50
      @temp50 25 дней назад

      @@krccmsitp2884 it is called tests. Are you testing the mapper library btw?

  • @ucanhovan8089
    @ucanhovan8089 2 месяца назад

    nice video

  • @moofymoo
    @moofymoo 3 месяца назад

    it goes in cycles - from everything needs a dto and use some auto mapper, look how cool it is, to get rid of bloat, all that auto mapper and dto's can go, because it does not add anything to business.

  • @yumyum7196
    @yumyum7196 3 месяца назад

    Are there really devs out there doubting if they should use DTOs???

    • @krccmsitp2884
      @krccmsitp2884 3 месяца назад

      Dunno, but there probably are devs that simply don't know DTOs (yet).

  • @oktjona
    @oktjona 3 месяца назад +1

    MAPSTER EASIER THAN AUTOMAPPER

  • @alexanderpoplooukhin7448
    @alexanderpoplooukhin7448 3 месяца назад

    You shouldn''t store your secrets in strings even in your model objects. Using DTOs depends on your model and how many kinds of clients use your API. If you have a rich model or you have a few kinds of clients (web app, mobile app), much better to use DTOs, because you will hide some details of you model and provide granulated and fittable contract for every client (Best for Frontend approach) in this case. If you use anemic model and you have only one kind of client of your API, much better don't use DTOs, because DTOs in this case will be redundancy.

  • @WattHowar-e9i
    @WattHowar-e9i 3 месяца назад

    Robinson Scott Jackson Brian Smith Sharon

  • @STech_Videos
    @STech_Videos 3 месяца назад

    How may i get connected with you for video editing process?