Stored Procedures with Entity Framework Core in .NET 6 🚀

Поделиться
HTML-код
  • Опубликовано: 13 июл 2024
  • 🚀 .NET Jumpstart Course: www.udemy.com/course/net-core...
    📧 Newsletter: newsletter.patrickgod.com/
    ❤️ Ko-fi: ko-fi.com/patrickgod
    ☕ Coffee: www.buymeacoffee.com/patrickgod
    💻 GitHub: github.com/patrickgod/EfCoreS...
    🐦 Twitter: / _patrickgod
    📓 Articles: / patrickgod
    🎥 Skillshare: www.skillshare.com/r/user/pat...
    🔥 Blazor E-Commerce Course: www.udemy.com/course/blazor-e...
    🔥 Blazor Bootcamp: www.udemy.com/course/blazor-w...
    💡 Online Course Lab: www.kristinagod.com/online-co...
    Table of Contents:
    00:00 Stored Procedures with Entity Framework Core in .NET 6 🚀
    01:02 The Web API Project with a SQL Server DB
    03:18 Call a simple Stored Procedure with no Parameters
    04:54 Call a simple Stored Procedure with Parameters
    08:34 Call a Stored Procedure with an Update and two Parameters
    11:34 A Sidenote on Affected Rows
    🙏MANY THANKS TO THESE LOVELY PEOPLE:
    @jacoviza
    Thomas McMeekin
    Ameet Jayawant
    JesperNielsen
    Paul
    @Alaffer
    Alvin Majid
    Slava Ukrayini
    Piotr Franczak
    Jan Trichter
    Tom
    H. Ali
    Ashley Gahl
    Daniel Viveros
    Mehmet Ali Ege
    Winther
    harry j
    @Alaffer
    Sam Catlow
    Jim
    Brian Williams
    Gonzo
    Jonas
    Ariel Sartor
    Andy Benson
    @stevelikespies
    Raphael Lukas
    James Goforth
    @williamdevine
    Doug Nelson
    Arif Hasanov
    @kohji1712
    @dlb78dlb
    Thomas Korsgaard
    FastTrak
    Jeff Sager
    Dan Moyer
    AlgoMarket
    Mennskr
    Simon
    Michael Mel
    Hermann Rösch
    Jim McNeal
    Kieron
    @mgrainger231
    Gerrit Esmeijer
    Axel
    Kareem Skinner
    Joaquim
    Alain Legrand
    Per Rieland
    @prodrigu75
    Greg
    Brendan Maunder
    Stageoner
    Andrew Campbell
    pascalditzfeld
    PovilasSimanskas
    jenö
    Marco Otilli
    Mark
    l33ter
    alibux
    g.dassel
    Luke Vincent
    mrcl
    Alain Legrand
    Thomas Werner
    István Csibor
    Grant Burdon
    @gianluigiconti
    Gerrit Esmeijer
    Illia
    Németh-Pók István
    Michael Mel
    Marko Zdilar
    GerryB
    @DADA_universe
    Domen Hren
    @heroesch
    Carey
    Peter De Tender
    Baris Keskin
    @Big_Bear_27390
    Mathias
    walter e watkins
    Günther Dassel
    Axel
    Josh
    Daniel Huber
    Fredric Adell
    Juan Carlos
    Manolis
    Pajani
    P.
    Jonas Granlund
    Bobby
    Kristina
    @xamarin007
    #DotNet #EfCore #PatrickGod

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

  • @codingbloke
    @codingbloke Год назад +49

    Always use the ExecuteSqlInterpolatedAsync and the FromSqlInterpolated instead of the older methods shown in this video. This will defend your API for SQL Injection attack.

    • @PatrickGod
      @PatrickGod  Год назад +9

      Good point! Thanks for sharing that! ☺️

    • @gymbez
      @gymbez Год назад +5

      Wouldn't using a stored procedure do this as well? Assuming you're not using dynamic sql of course.

  • @tigshinigami
    @tigshinigami Год назад

    Thanks for sharing your time and knowledge with the community, as always an excellent video.

  • @user-te4tn1vj5r
    @user-te4tn1vj5r Год назад +1

    Thank you!!

  • @albertosena4730
    @albertosena4730 Год назад

    Thank you!

  • @AbhishekGupta-hs8nh
    @AbhishekGupta-hs8nh Год назад +1

    Nice explanation 👍

  • @PontusWittenmark
    @PontusWittenmark Год назад +8

    I always use Scaffold-dbcontext rather than migrations as I find it a much more clean work flow. Is there a way to get the sprocs now?
    I recall we used to be able to do this back in the day (was it ef or linqtosql?). It was great, it generated a method on the context with mapped parameters and return types 👌

  • @codemonk1999
    @codemonk1999 Год назад +8

    In particular, never pass a concatenated or interpolated string ($"") with non-validated user-provided values into FromSqlRaw or ExecuteSqlRaw. The FromSqlInterpolated and ExecuteSqlInterpolated methods allow using string interpolation syntax in a way that protects against SQL injection attacks.

    • @WarrenLeggatt
      @WarrenLeggatt Год назад +3

      A wise thing. Better than having a visit from the user ... Timmy"; Drop table users
      :)

  • @moinin25148
    @moinin25148 Год назад

    It's clear explanation 👌

  • @AkshayMeshram09
    @AkshayMeshram09 Год назад

    Thanks

  • @LUISEGONZALEZL
    @LUISEGONZALEZL Год назад

    How would it be if the stored procedure has several parameters but some are optional or depending on what is required only some may be needed?

  • @saritalad8923
    @saritalad8923 11 месяцев назад

    Thanks , Can you tell if Oracle Entity Framework also we can work with stored Procedures ?
    and can you show one example of inner join in stored procedure ?

  • @noelfrancisco5778
    @noelfrancisco5778 Год назад +1

    Is there a way to call a stored procedure that returns compounded data (union of tables) without using third-party nuget package? TIA

  • @legionsman7476
    @legionsman7476 Год назад

    most stored procedures return info from multiple table sources. EF Core cannot use sp's with JOINS in them or passing multiple parameters, correct?

  • @dilipgautam9941
    @dilipgautam9941 Год назад +1

    Hi Patrick could you please record a session on CRUD operation with YugabyteDB in .Net Core 6

  • @zameer.vighio
    @zameer.vighio Год назад +2

    Hi Patrick, i hope you are fine & doing well,
    is it safe to pass parameters as you passed to query? i hope there isn't any SQL Injection Issue?
    please confirm about SQL Injections with these queries... if any then how to avoid ?
    Thanks

  • @dev99vn93
    @dev99vn93 Год назад

    Thanks you, this video is very good.
    Can you create a video subject ' hangfire with .Net'.

  • @DanielTorres-oj7hb
    @DanielTorres-oj7hb Год назад

    do you have any example with output parameters?

  • @francosaavedra9771
    @francosaavedra9771 Год назад +1

    thanks for sharing this, you are awesome...

    • @PatrickGod
      @PatrickGod  Год назад

      Thank you so much. Appreciate it. 😊

  •  Год назад

    Hello my friend, you have any example whit call stored procedure from project in clean arquitecture?

  • @mhmdhussein7739
    @mhmdhussein7739 Год назад

    what is best for heigh performance use store procedure or else what ??

  • @kakdiyaamit6625
    @kakdiyaamit6625 Год назад

    Please make one video of order and order details using store procedure

  • @thieptrantrung
    @thieptrantrung Год назад +2

    thanks you, very good.!!!

    • @PatrickGod
      @PatrickGod  Год назад

      Thanks! Glad I could help! 😊

  • @JarretteSchule
    @JarretteSchule Год назад +5

    One thing I'm stuck on, and isn't shown in this video is how to run a SELECT SP that returns a set of results that doesn't correspond exactly to a table. It's a complex stored procedure that returns a series of joins, etc.
    ExecuteSqlRawAsync only returns the number of rows affected and I can't run [TableName].FromRawSql since there is no corresponding scaffolded class (I'm using DB first since the database is huge and already existing).

    • @codingbloke
      @codingbloke Год назад

      Switch to Dapper, for that sort of thing especially if you are just doing read only operations. Even when you want to update the data you can use to Dapper acquire the objects with raw sql or SPs then attach those objects to a DbContext if you want to update them.

    • @robsonarruda3722
      @robsonarruda3722 Год назад

      if your procedure returns more than one dataset, you can convert that complex data to json (FOR JSON PATH), map the procedure result to a keyless dto and then deserialize

    • @Greenthum6
      @Greenthum6 Год назад

      Try EF Core Power Tools to scaffold stored procs into code. This will show you how the fields and input parameters are configured for the query.

    • @AbhaySingh-lf4oy
      @AbhaySingh-lf4oy Год назад

      @@robsonarruda3722 Hey bro, can you please tell me how to do it. I tried but it didn't work I guess I am doing something wrong. Please explain this in more detail.

  • @muhammadnurali4347
    @muhammadnurali4347 Год назад

    Can i do it using dotnet cli ? I use linux, and can't do it using visual studio

  • @user-gi2ls8xt5s
    @user-gi2ls8xt5s Год назад

    is the FromSqlRaw safe? against SqlInjection?

  • @jeffalan6441
    @jeffalan6441 Год назад +2

    As others have poineted out you should have parameterised your userId: var p1 = new SqlParameter("@userId", userId); To prevent sql injections.

  • @yazanalkobari
    @yazanalkobari Год назад

    Hi,
    You can return objects with a relationship using a keyless entity.

    • @shoguny9939
      @shoguny9939 Год назад

      Hi Yazan, I've been looking for a guide on using stored procedure to return object into my viewmodel(keyless entity). Appreciate if you can provide a guide on how to do this? Thanks!

  • @amralmotalles7991
    @amralmotalles7991 Год назад

    Thank you very much , only one question , what is your professional opinion regarding using Stored Procedures or coding the logic on service layer side ? appreciate your answer very much.

    • @mmarques_mdc
      @mmarques_mdc Год назад

      Imo, stored procedures are a great way to support quick changes to your T-SQL code by you or third-parties, but most of the time you'll get locked-in to database vendor and in the long run this might become an issue.

    • @oddikaro8236
      @oddikaro8236 Год назад

      SP is the best way of doing things. Faster, clearer, no need to learn any custom tech to do something you already know (sql), and no intermediate layer like ef dapper or anything. You need to know C#, .net, sql. Be good at that. This video (7:00) is a good example of the limitations of an ORM. Who is going to change DB in practice? From sql server to oracle...come on nobody.

  • @bytechanneltv
    @bytechanneltv Год назад

    Hi Patrick! Great video - thanks a lot. But one very interesting topic is not explained in your video: How can I create a stored procdedure within the DbContext? This DbContext would be the best place to create a stored procedure if a new database will be set up (Code first migrations). Thanks and best greetings from Austria. Jürgen

    • @luisonio11
      @luisonio11 Год назад

      You could create an empty migration, and add the code to create the SP. when you execute the migration, the SP are going to be created. Is the best way to create the SP from EF.

  • @hasanmougharbel8030
    @hasanmougharbel8030 Год назад

    Hey there, glad to meet again.
    I am working my way around sql language and still have one major enquiry.
    Is there a command to test an SQL query without executing it?
    I wish that i would play with my code and to return results without altering my physical data in the server.
    Thanks a lot for taking care of this.

    • @bassethoundgang2800
      @bassethoundgang2800 Год назад +1

      if you have SQL that updates a database and you don't want to actually update, start your query with BEGIN TRAN. Then run the SQL. When the sql is done, you can run ROLLBACK TRAN
      All of this was done in SQL Server Management Studio
      CREATE TABLE [dbo].[Dogs](
      [id] [int] IDENTITY(1,1) NOT NULL,
      [DogBreedName] [varchar](50) NULL,
      CONSTRAINT [PK_DogBreeds] PRIMARY KEY CLUSTERED
      (
      [id] ASC
      )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
      ) ON [PRIMARY]
      GO
      insert into Dogs(dogbreedname)
      values('Basset Hound')
      select * from Dogs
      ---you should see one row for the basset hound
      begin tran
      insert into Dogs(dogbreedname)
      values('Beagle')
      select * from Dogs
      ---you should see two rows now. New row for beagle
      rollback tran
      select * from Dogs
      should see the basset row now

    • @hasanmougharbel8030
      @hasanmougharbel8030 Год назад

      @@bassethoundgang2800 I was only wondering what does this part of your code does or indicate?
      CLUSTERED
      (
      [id] ASC
      )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
      ) ON [PRIMARY]
      GO
      thanks a lot

  • @Christobanistan
    @Christobanistan Год назад

    what if the sproc just returns an int?

  • @TXPhoenix79
    @TXPhoenix79 Год назад

    You're getting that alert because to changed the code logic and you already have the app running with the old code complied.

  • @cortes-d-impacto
    @cortes-d-impacto Год назад +2

    What is the difference between creating an API to perform these operations or creating an SP to do the same?

    • @FarukLuki111
      @FarukLuki111 Год назад +2

      Strictly seen you could change the SP without the need of changing any code and therefore without the need of re-deploying the application! BUT I would not suggest doing that

  • @shambhupandey8436
    @shambhupandey8436 Год назад

    when I add migration and update the database it continuously add the data procedure [dbo].[some random name] which is already exit what is the solution for this please help

  • @khoaang2315
    @khoaang2315 Год назад

    Hi you, I want to ask Why direction hitpoints/{characterId}/{hitoints} in HttpGet
    Thank you

  • @muntheralkhwaldeh728
    @muntheralkhwaldeh728 Год назад

    thank you so much i try it in insert procedure but alwas show error (syntax error at or near "mark") thats first argument ? do you know what that probelm

  • @orionlegalsupplies9743
    @orionlegalsupplies9743 Год назад

    how to write scalar query in .net core 6 ?

  • @CodeLife264
    @CodeLife264 11 месяцев назад

    I have a stored procedure which contains inner join. I'm confused about which model to pass with _context while calling raw sql?

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

      You would need to create a new model to represent the data returned from the stored procedure.

  • @dasfahrer8187
    @dasfahrer8187 Год назад

    Good video. Don't see the Github link in the description tho.

    • @PatrickGod
      @PatrickGod  Год назад +1

      github.com/patrickgod/EfCoreStoredProcedureTutorial 😉

    • @PatrickGod
      @PatrickGod  Год назад +1

      And thank you! 😊

  • @junsato2049
    @junsato2049 Год назад

    This only works if the stored proc result cleanly maps to a known entity, so it's not really real life ready. How do I get EF to analyze the parameters and results of stored procedures, and map stored proc names to methods?

    • @zameer.vighio
      @zameer.vighio Год назад

      it's better to use Stored Procedures only for UPDATE & DELETE OPERATIONS to avoid first fetch record then call UPDATE OR DELETE method in LINQ...
      for fetching data simply use LINQ....

  • @Bigbacon
    @Bigbacon 7 месяцев назад

    Guessing you can't auto generate classes of SPs and Views like you could in framework entity 6?

  • @DanielTorres-oj7hb
    @DanielTorres-oj7hb Год назад

    I From Nicaragua Excuse my english, hahaha

  • @clashclan4739
    @clashclan4739 Год назад +1

    For all youtubers who post educational content pls avoid background music. It totally annoying

  • @huyang2885
    @huyang2885 Год назад

    100đ

  • @StonkExchange
    @StonkExchange Год назад

    bro delete this video youre getting ppl sqlinjected