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

Поділитися
Вставка
  • Опубліковано 3 жов 2024
  • 🚀 Join the .NET Web Academy: dotnetwebacade...
    💻 Use Code LONGERNIGHTS to get 20% off on any course or plan!
    🐦 Let's get social on Twitter/X: / _patrickgod
    🔗 Let's connect on LinkedIn: / patrickgod

КОМЕНТАРІ • 46

  • @dasfahrer8187
    @dasfahrer8187 3 дні тому +6

    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).

  • @yumyum7196
    @yumyum7196 2 дні тому +4

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

  • @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

  • @mtranchi
    @mtranchi 3 дні тому +3

    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:
      ua-cam.com/video/GWYhtksrmhE/v-deo.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?"

    • @gppsoftware
      @gppsoftware 2 дні тому

      Need to be careful with this approach because you can end up with models being sent to a UI which are basically the same as a database structure. It results in high coupling between UI and database. And yes, I know lots of people do this!

    • @fifty-plus
      @fifty-plus 2 дні тому

      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.

  • @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?

  • @JayTandon-nq9du
    @JayTandon-nq9du 3 дні тому +3

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

  • @ArmandoPineda4
    @ArmandoPineda4 2 дні тому

    You're the best!!

  • @aymenbachiri-yh2hd
    @aymenbachiri-yh2hd 2 дні тому

    Thanks you so much

  • @path_selector
    @path_selector 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

  • @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 2 дні тому +2

      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 2 дні тому

      @@fusedqyou yes i forgot that!

  • @rick_info_dev_pyt
    @rick_info_dev_pyt День тому

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

  • @AthelstanEngland
    @AthelstanEngland 2 дні тому

    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.

  • @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?

  • @nieuwveen
    @nieuwveen День тому

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

  • @gppsoftware
    @gppsoftware 2 дні тому

    DTO's are a very handy tool, however, most people simply make them a copy of their database tables, thereby loosing their value.
    The video gave an example of using DTO's to output data from an API. This is certainly valid, but not all API's are exposed externally. Some are exposed to support a Javascript API. In this scenario, DTO's are are really 'view models'. The problem I come across frequently is that most developers don't know the difference between the two and in most cases, create DTOs and View Models that are copies of their database tables. This means that they hit their API for every table, thereby coupling a UI to a backend. A view model is designed to combine all the data necessary for a view so that there is only one API call which is decoupled and independent of the database structure.

  • @Hasan10-oh7vl
    @Hasan10-oh7vl 12 годин тому

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

  • @STech_Videos
    @STech_Videos 13 годин тому

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

  • @krccmsitp2884
    @krccmsitp2884 3 дні тому

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

  • @Luisllaboj19
    @Luisllaboj19 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. :(

  • @Rick-mf3gh
    @Rick-mf3gh 3 дні тому +2

    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 2 дні тому

      what is the drawbacks of using AutoMapper?

    • @gppsoftware
      @gppsoftware 2 дні тому

      @@kristiadhy Performance for one. All generic mappers use reflection, so compared to directly assigning properties in code yourself, it is very slow, especially in high performance applications. Reflection involves looking through lists and marshalling objects and object types. Direct assignment just copies one variable value to another.

    • @kristiadhy
      @kristiadhy 2 дні тому

      @@gppsoftware so what is the better option then?

    • @gppsoftware
      @gppsoftware 2 дні тому

      @@kristiadhy I'd say coding the mapping yourself and not using a mapper. If you code this yourself, you can guarantee that if you compile your code successfully, it will work. Mappers operate at runtime using reflection so code will compile but you won't find out if it works until you run/test it.

    • @kristiadhy
      @kristiadhy 2 дні тому

      @@gppsoftware I see, thank you

  • @yumyum7196
    @yumyum7196 2 дні тому

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

    • @krccmsitp2884
      @krccmsitp2884 2 дні тому

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

  • @oktjona
    @oktjona 3 дні тому +1

    MAPSTER EASIER THAN AUTOMAPPER

  • @bauminator610
    @bauminator610 2 дні тому

    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 2 дні тому

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

    • @bauminator610
      @bauminator610 2 дні тому

      @@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.

  • @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.

  • @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.

  • @fusedqyou
    @fusedqyou 2 дні тому

    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 2 дні тому

      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 2 дні тому

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

  • @STech_Videos
    @STech_Videos 17 годин тому

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