Entity Framework Core
18 TopicsProblem with the startswith function in NET 9
Hi everyone, I have this request with Odata: http://localhost:5194/NationalStates?$filter=startswith(state, 'NE') This works correctly up to version 8.0.14 for the following packages: MySql.EntityFrameworkCore Microsoft.Extensions.DependencyInjection.Abstractions Microsoft.EntityFrameworkCore among others... When I update these packages to version 9.0.0 or later, they stop working and give an internal mapping error. Any clues about this?78Views0likes0Comments.NET Data Community Standup - New CLI Edition of EF Core Power Tools
In today's standup, Erik will demonstrate the new CLI edition of EF Core Power Tools and show how he used a number of community NuGet packages to improve the user experience when creating a CLI tool. Featuring: Erik EJ (@ErikEJ), Arthur Vickers (@ajcvickers), Shay Rojansky (@ShayRojansky) #EFCore #PowerTools #Community483Views1like0Comments.NET Data Community Standup - Collections of primitive values in EF Core
In this episode of the .NET Data Community Standup, the .NET Data Access team dive into new support for collections of primitive values, just released in EF Core 8 Preview 4. Collections of a primitive type can now be used as properties of an entity type and will be mapped to a JSON column in the relational database. In addition, parameters of primitive values can be passed to the database. In either case, the native JSON processing capabilities of the database are then used to exact and manipulate the primitive values, just as if they were in a table. This opens up powerful query possibilities, as well as optimizations to common problems such as translating queries that use Contains. Featuring: Arthur Vickers (ajcvickers), Shay Rojansky (@shayrojansky) #EntityFramework #DotNet #EFCore1.2KViews0likes0CommentsAzure Developers - .NET Day 2023
Experience Cloud Computing in Full Force with .NET on Azure. See the full agenda: https://learn.microsoft.com/events/learn-events/azuredeveloper-dotnetday/ As a .NET developer building for the cloud, do you want to stay ahead of the curve and maximize your potential? Join us to discover the latest services and features in Azure designed specifically for .NET developers. You'll learn cutting-edge cloud development techniques that can save you time and money, while providing your customers with the best experience possible. During the event, you'll hear directly from the experts behind the most sought-after cloud services for developers, spanning app development/compute, data services, serverless computing, cloud-native computing, and developer productivity. Don't miss this chance to participate and engage with the team throughout the day. Join us and take your cloud development skills to the next level! #azure #azuredevelopers #azurefunctions #azurecontainerapps #azuredevcli1.4KViews0likes0Comments.NET Data Community Standup - EF Core internals: IQueryable, LINQ and the EF Core query pipeline
In this standup, we'll dive deep under the hood to see how EF Core processes LINQ queries, translates them to SQL and executes them on your database. We'll introduce key concepts such as IQueryable and LINQ providers, and see how EF Core uses caching to make your querying lightning-fast. Join us to understand how the magic works!1.1KViews0likes0CommentsEntity Framework Community Standup - Hot Chocolate 12 and GraphQL 2021
Hot Chocolate 12 allows for more schema-building options with deeper integrations into EF core. Hot Chocolate has already implemented the new GraphQL October 2021 spec, and we will explore the new capabilities. We now support the complete stream and defer spec and will look into these new data fetching capabilities. Community Links: https://www.theurlist.com/efcore-standup-2021-12-01 Featuring: Jeremy Likness (@JeremyLikness), Michael Staib (@michael_staib) Get your questions answered on the Microsoft Q&A for .NET - https://aka.ms/dotnetqa Learn .NET with free self-guided learning from Microsoft Learn: http://aka.ms/learndotnet #efcore #graphql #webapi601Views0likes0CommentsLearn C# with CSharpFritz - Data Access with Entity Framework
Your application needs to interact with a database, so how do we connect to one with C#? In this session, Jeff Fritz talks about Entity Framework and how you can use it to read, write, and build databases for your application Community Links: https://github.com/csharpfritz/csharp_with_csharpfritz Featuring: Jeff Fritz (@csharpfritz) Get your questions answered on the Microsoft Q&A for .NET - https://aka.ms/dotnetqa Learn .NET with free self-guided learning from Microsoft Learn: http://aka.ms/learndotnet #beginner #csharp #entityframework469Views0likes0CommentsFire-and-Forget Methods in C# — Best Practices & Pitfalls
When building modern applications, there are often situations where you want to perform tasks in the background without holding up the main flow of your application. This is where “fire-and-forget” methods come into play. In C#, a fire-and-forget method allows you to run a task without awaiting its completion. A common use case is sending a confirmation email after creating a user, but this also brings some limitations, particularly when dealing with scoped services. In this blog, we’ll walk through an example and explain why scoped services, like database contexts or HTTP clients, cannot be accessed in fire-and-forget methods. Why Fire-and-Forget? Fire-and-forget is useful in situations where you don’t need the result of an operation immediately, and it can happen in the background, for example: Sending emails Logging Notification sending Here’s a common scenario where fire-and-forget comes in handy: sending a welcome email after a user is created in the system. public async Task<ServiceResponse<User?>> AddUser(User user) { var response = new ServiceResponse<User?>(); try { // User creation logic (password hashing, saving to DB, etc.) _context.Users.Add(user); await _context.SaveChangesAsync(); // Fire-and-forget task to send an email _ = Task.Run(() => SendUserCreationMail(user)); response.Data = user; response.Message = user.FirstName + " added successfully"; } catch (Exception ex) { // Error handling } return response; } The method SendUserCreationMail sends an email after a user is created, ensuring that the main user creation logic isn’t blocked by the email-sending process. private async Task SendUserCreationMail(int id) { // This will throw an exception be _context is an scoped service var user = await _context.Users.FindAsync(id); var applicationUrl = "https://blogs.shahriyarali.com" string body = $@" <body> <p>Dear {user.FirstName},</p> <p>A new user has been created in the system:</p> <p>Username: {user.Username}</p> <p>Email: {user.Email}</p> <p>Welcome to the system! Please use the provided username and email to log in. You can access the system by clicking on the following link:</p> <p><a href='{applicationUrl}'>{applicationUrl}</a></p> <p>Best regards,</p> <p>Code With Shahri</p> </body>"; var mailParameters = new MailParameters { Subject = $"New User Created - {user.Username}", Body = body, UserEmails = new List<UserEmail> { new() { Name = user.FirstName, Email = user.Email } } }; await _mailSender.SendEmail(mailParameters); } In the code above, the SendUserCreationMail method is executed using Task.Run(). Since it's a fire-and-forget task, we don’t await it, allowing the user creation process to complete without waiting for the email to be sent. The Problem with Scoped Services A major pitfall with fire-and-forget tasks is that you cannot reliably access scoped services (such as DbContext or ILogger) within the task. This is because fire-and-forget tasks continue to run after the HTTP request has been completed, and by that point, scoped services will be disposed of. For example, if _mailSender was scoped services, they could be disposed of before the SendUserCreationMail task completes, leading to exceptions. Why Can’t We Access Scoped Services? Scoped services have a lifecycle tied to the HTTP request in web applications. Once the request ends, these services are disposed of, meaning they are no longer available in any background task that wasn’t awaited within the request lifecycle. In the example above, since the fire-and-forget email sending isn’t awaited, attempting to use scoped services will throw an ObjectDisposedException. To safely access scoped services in a fire-and-forget method, you can leverage IServiceScopeFactory to manually create a service scope, ensuring that the services are available for the task. private async Task SendUserCreationMail(int id) { // Create a service scope. using var scope = _serviceScopeFactory.CreateScope(); var _context = scope.ServiceProvider.GetRequiredService<DataContext>(); var user = await _context.Users.FindAsync(id); var applicationUrl = "https://blogs.shahriyarali.com" string body = $@" <body> <p>Dear {user.FirstName},</p> <p>A new user has been created in the system:</p> <p>Username: {user.Username}</p> <p>Email: {user.Email}</p> <p>Welcome to the system! Please use the provided username and email to log in. You can access the system by clicking on the following link:</p> <p><a href='{applicationUrl}'>{applicationUrl}</a></p> <p>Best regards,</p> <p>Code With Shahri</p> </body>"; var mailParameters = new MailParameters { Subject = $"New User Created - {user.Username}", Body = body, UserEmails = new List<UserEmail> { new() { Name = user.FirstName, Email = user.Email } } }; await _mailSender.SendEmail(mailParameters); } Conclusion Fire-and-forget methods in C# are useful for executing background tasks without blocking the main application flow, but they come with their own set of challenges, particularly when working with scoped services. By leveraging techniques like IServiceScopeFactory, you can safely access scoped services in fire-and-forget tasks without risking lifecycle management issues. Whether you're sending emails, logging, or processing notifications, ensuring proper resource management is crucial to prevent errors like ObjectDisposedException. Always weigh the pros and cons of fire-and-forget and consider alternative approaches like background services or message queuing for more robust solutions in larger systems. To explore more on this topic, you can check out the following resources on Microsoft Learn: Task.Run Method Task asynchronous programming model10KViews2likes2CommentsGetting Started with Entity Framework Core
Today, we’ll discover a method to integrate database support into an ASP.NET Core API using Entity Framework Core. A database stands as a vital component in many applications, serving as the storage and retrieval hub for data. Traditionally, developers had to convert C# data access code into SQL statements, a process open to errors and time-consuming. However, with Entity Framework Core, you can delegate the tasks to the framework, allowing you to concentrate on application development.747Views0likes0Comments