logo
down
shadow

How to get transient DbContext in ASP.NET MVC Core?


How to get transient DbContext in ASP.NET MVC Core?

By : thesis
Date : October 21 2020, 08:10 PM
this one helps. I have the following in Startup.cs: , You need to create a scope manually something like this:
code :
using (var scope = serviceProvider.CreateScope())
{
    var scopedServices = scope.ServiceProvider; 
    scopedServices.GetRequiredService<MyDbContext>();

     ...
}


Share : facebook icon twitter icon
EntityFrameworkCore quite a dbcontext or should Separating DbContext In .Net Core Like Bounded Context For Getting Perfo

EntityFrameworkCore quite a dbcontext or should Separating DbContext In .Net Core Like Bounded Context For Getting Perfo


By : J055
Date : March 29 2020, 07:55 AM
I wish this help you Its not necessarily a performance issue as the DbContext uses IQueryable for your DbSets so each 'table' isnt materialized until you call ToList(), First(), etc. I have worked on projects (not my design) that have used over a 100 tables in a single context and the bottlenecks were never from a large DbContext. It just made the whole project unweildy and not something I would want to do again.
For larger projects whether its .net core or .net <=4.5 I would definitely go the bounded context route but structured from a DDD standpoint. Juli Lerman has written many blog posts about this and of course there is the blue book by Eric Evans which is the DDD bible.
Configuring Dbcontext as Transient

Configuring Dbcontext as Transient


By : Hassan Rashed
Date : March 29 2020, 07:55 AM
hop of those help? In ASP.NET Core / EntityFramework Core, the services.AddDbContext<> method will add the specified context as a scoped service. It's my understanding that that is the suggested lifetime management for the dbcontext by Microsoft. , The lifetime is a parameter on AddDbContext<>(). See example:
code :
services.AddDbContext<ApplicationDbContext>(options =>
         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), 
         ServiceLifetime.Transient);
Dbcontext object transient in dotnet core

Dbcontext object transient in dotnet core


By : Luznery Del Carmen V
Date : March 29 2020, 07:55 AM
To fix the issue you can do I'm creating an webapi application in dotnet core with entity framework. When I gone through documentation. I can use DI to inject the dbcontext object in dotnet core. But when I'm doing this the whole application using one dbcontext object. How do I make the dbcontext as transient? If any example is there it will really help me. , I`ve already done this using a separated statement.
code :
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DataAccess.XXXXContext>(options => options.UseMySQL(Configuration["ConnectionStrings:DefaultConnection"]));

    services.AddTransient<DataAccess.XXXXContext>();
}
EF Core - Disposable DbContext and Attach() - or - DbContext as member - or - Disconnected Entities

EF Core - Disposable DbContext and Attach() - or - DbContext as member - or - Disconnected Entities


By : SameerD
Date : March 29 2020, 07:55 AM
I hope this helps . Side Note:
in MVVM ObservableCollection.CollectionChanged is supposed to inform View about changes in Model, resp ViewModel. I would not recommend to let View modify ObservableCollection and then use CollectionChanged to reflect the changes in ViewModel. Try to keep ViewModel -> View notification flow, not the other direction.* Every change is done in ViewModel and reflected in the View.
code :
public class YourPageViewModel
{
    private readonly ObservableCollection<VendorItemVm> _deletedVendors = new ObservableCollection<VendorItemVm>();
    public List<VendorItemVm> Vendors { get; } = new List<VendorItemVm>();

    void Add()
    {
        Vendors.Add(new VendorItemVm
        {
            IsNew = true,
            Id = new Guid(),
            UserName = "New Vendor",
        });
    }

    void Remove(VendorItemVm vendor)
    {
        Vendors.Remove(vendor);
        _deletedVendors.Add(vendor); 
    }

    async Task Load()
    {
        using(var db = new DbContext())
        {
            var vendors = db.Vendors.AsNoTracking().ToList();
            foreach(var entity in vendors)
            {
                Vendors.Add(new VendorItemVm
                {
                    Id = entity.Id,
                    Name = entity.Name,
                });
            }
        }
    }

    async Task Save()
    {
        using (var db = new DbContext())
        {
            //convert viewmodels to entities
            var newVendorsEntities = Vendors
                .Where(v => v.IsNew)
                .Select(v => new Vendor
                {
                    Id = v.Id,
                    UserName = v.UserName,
                    TimeSpan = DateTime.Now,
                })
                .ToArray();

            //add new entities
            foreach (var vm in Vendors.Where(v => v.IsNew))
            {
                var entity = new Vendor
                {
                    Id = vm.Id,
                    UserName = vm.UserName,
                    TimeSpan = DateTime.Now,
                };
                db.Vendors.Add(vendor);
            }

            //delete removed entities:
            foreach(var vm in _deletedVendors)
            {
                var entity = new Vendor { Id = vm.Id };
                db.Vendors.Attach(entity);
                db.Ventors.Remove(entity);
                db.Vendors.Add(vendor);
            }

            await db.SaveChangesAsync();

            //reset change tracking
            foreach (var vm in Vendors) vm.IsNew = false;
            _deletedVendors.Clear();
        }
    }
}
public class YourPageViewModel
{
    MyDbContext _myUoW;
    public ObservableCollection<Vendor> Vendors { get; } = new ObservableCollection<Vendor>();

    void Add()
    {
        var entity = new Vendor
        {
            Id = new Guid(),
            UserName = "New Vendor",
        };
        Vendors.Add(entity)
        _myUoW.Vendors.Add(entity);
    }

    void Remove(VendorItemVm vendor)
    {
        Vendors.Remove(vendor);
        _myUoW.Vendors.Attach(entity);
        _myUoW.Vendors.Add(entity);
    }

    async Task Load()
    {
        using(var db = new MyDbContext())
        {
            Vendors = db.Vendors.AsNoTracking.ToList();
            foreach(var entity in vendors) Vendors.Add(entity);
        }
        _myUoW = new MyDbContext();
        //if you want to track also changes to each vendor entity, use _myUoW to select the entities, so they will be tracked. 
        //In that case you don't need to attach it to remove
    }

    async Task Save()
    {
        //add new entities and delete removed entities
        _myUoW.SaveChanges();

        //reset change tracking
        _myUoW.Dispose();
        _myUoW = new MyDbContext();
    }
}
Create a new DbContext or use the injected DbContext when calling a stored procedure in Entity Core?

Create a new DbContext or use the injected DbContext when calling a stored procedure in Entity Core?


By : Sanjeev Tiwari
Date : March 29 2020, 07:55 AM
Does that help There shouldn't be any reason to not use the injected one.
If you are asking just because you are only reading the data and want it to be quick, and you're worried about tracking or something, you should just call .AsNoTracking() when calling the DB for your stored proc.
Related Posts Related Posts :
  • How do request a correct access token in ASP.NET Core for Azure AD to access Microsoft Graph
  • How to run a .NET Core console application on Linux
  • UI not updating for bound element
  • C# Odata v4 open type raw values
  • DocumentFormat.OpenXml Modify Creator Propery of Document
  • How to SetBasePath in ConfigurationBuilder in Core 2.0
  • ASP MVC5 public readonly variable changes value when it should not
  • How to conditionally select item from hashset with queryable linq?
  • Progress Bar C# not showing the real progress
  • Correct logic to reconnect in SignalR with HubConnection
  • ComboBox with two or more sections
  • .NET listbox to SQLite DB
  • C# Ninject binding from Dictionary<Type, Type>
  • asp.net mvc -view displaying real-time progress status
  • Getting reference to dependent in service with generic type
  • Implementing EqualityCompare vs overriding GetHashCode and Equals
  • C# Linq Find all indexes of item in List<int> within another List<int>
  • XML image how to display at data grid columns in c#.net
  • How to override Equals and GetHash of HashSet
  • Creating Windows authentication and SQL Server authentication in login form
  • How to interop with Azure Service Bus topics created by MassTransit using Rebus?
  • MVC 5 Google Calendar Integration
  • C# - Use parallel arrays to calculate cost of a phone call in GUI
  • Use a int in entire code
  • How to display newly added element at the top of StackPanel in WPF?
  • T4MVC is generating T4MVC.cs and T4MVC1.cs
  • Remove blur effect on certain controls inside UserControl
  • Sql Transcation Query to Linq Query in Wcf Rest Service
  • Setting AWS S3 credentials in C# app
  • does not contain in an ObservableCollection
  • App doesn't run it crashed directly after I started it
  • Is it possible in Entity Framework MVC application to run .sql scripts on a different database
  • Type Inference with Deconstruct tuple assignment extension methods
  • Setting up mock objects for EF dbcontext to test repository methods
  • Using C# in XSLT with MSXSL 6.0
  • Absolute positioning of UIElement in FlowDocument in WPF
  • Display debuggers not showing up in Visual Studio 2017
  • Discord.NET Users playing the same game
  • Azure function output API call to 3rd party service
  • Unable to determine the relationship represented by navigation property ASP.NET core 2.0 Entity Framework
  • Regex to find group of Regex inside a word
  • When calling a method, when to reference the class, and when to reference the object?
  • AmazonCloudWatchLogsClient async methods failing with no error
  • Create FileStream in memory instead of saving a physical file on disk
  • ViewBag data coming from ActionFilter is persisting in session even after database
  • ERROR: the name 'lvSubCategories' does not exist in the current context
  • Why datetime can't recognise the string?
  • Getting 500 error while requesting to webservice using Ajax AutoCompleteExtender
  • The property 'x' is not a navigation property of entity type 'y'
  • ASP.NET MVC - How to generate empty input boxes in loop when model is empty?
  • Need help writing regular expression
  • Add/remove buttons to a panel with an arraylist c#
  • Linq .Where(type = typeof(xxx)) comparison is always false
  • Using EF6 Code First without migrations to an existing db how do I specify column names of the many to many join table?
  • C# - Using Thread.Sleep precisely in a console application
  • Add item to a List<Tuple> inside another list
  • Double[,], inversion C#
  • Counting a string to ensure the input is within a min/max boundary
  • Assign invalidValue to Enum variable (why is this not throwing an Exception?)
  • Namespace or type specified in the project-level Imports 'System.Threading.Tasks' doesn't contain any public member or c
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org