Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException

Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException

Content Index :

Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
Tag : chash , By : qba73
Date : January 12 2021, 09:11 PM

I wish did fix the issue. There are many ways to solve this issue but I'll just give you my prefered way.
First, you have to create a second DbContext class that has access to your Users database set, and that is not going to have a Query Filter applied to it.
public class UserDbContext : DbContext 
    public DbSet<ApplicationUser> Users { get; set; }  
public class TenantProvider : ITenantProvider
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly UserDbContext _userDbContext;

    private Guid _tenantId;

    public TenantProvider(UserDbContext userDbContext,
                          IHttpContextAccessor httpContextAccessor)
        _userDbContext = userDbContext;
        _httpContextAccessor = httpContextAccessor;

    private void SetTenantId()
        if (_httpContextAccessor.HttpContext == null)
            // Whatever you would like to return if there is no request (eg. on startup of app).
            _tenantId = new Guid();

        _tenantId = _userDbContext.Users.FirstOrDefault(u => u.UserName == _httpContextAccessor.HttpContext.User.Identity.Name)?.TenantId;

    public Guid GetTenantId()
        return _tenantId;
public interface ITenantProvider
    Guid GetTenantId();
services.AddScoped<ITenantProvider, TenantProvider>();
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>,
ApplicationUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
    private readonly IHttpContextAccessor _contextAccessor;

    private Guid _tenantId;

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor contextAccessor, ITenantProvider _tenantProvider)
        : base(options)
        _contextAccessor = contextAccessor;
        _tenantId = _tenantProvider.GetTenantId();


    public DbSet<ApplicationUser> ApplicationUser { get; set; }
    public DbSet<Tenant> Tenant { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)

        builder.Entity<Tenant>().HasQueryFilter(e => e.TenantId == _tenantId);
        builder.Entity<ApplicationUser>().HasQueryFilter(e => e.TenantId == _tenantId);            

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Resolving 'No key Defined' errors while using OnModelCreating with ApplicationDbContext?

Tag : chash , By : amorican
Date : March 29 2020, 07:55 AM
Does that help I've been trying to create navigation properties for my collection types and I found this example of how one person accomplished it using OnModelCreating. I gave it a try in my MVC 5 application and I recieved this error when trying to update my database: , You might have to add something like the following to OnModelCreating
modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });

GetTable in ApplicationDbContext : IdentityDbContext<ApplicationUser>

Tag : chash , By : Bjørn Lyngwa
Date : March 29 2020, 07:55 AM
around this issue Since you're using EF6 queries are automatically compiled regardless of the .net framework the code is running against.
The link you provided in your question is dated from 2009 when it made sense to pre-compile queries.

MVC5 Referencing ApplicationDbContext : IdentityDbContext<ApplicationUser>

Tag : chash , By : dbarbot
Date : March 29 2020, 07:55 AM
Hope that helps You are still referencing the old namespace and class. You need to change it to the new context. And since you are already including the using RecreationalServicesTicketingSystem.Models then all you need to do is remove the old referenced namespace.
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using RecreationalServicesTicketingSystem.Models; // this is the namespace that has the new context
using System.Collections.Generic;

internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext> //References the new one now
    public Configuration()
        AutomaticMigrationsEnabled = false;

    protected override void Seed(ApplicationDbContext context)//References the new one now
    //...other code removed for prebity

ApplicationDbContext.OnModelCreating(ModelBuilder): no suitable method found to override

Tag : chash , By : jaredsmiller
Date : March 29 2020, 07:55 AM
Hope this helps According to the documentation, the OnModelCreating method takes a DbModelBuilder, not a ModelBuilder.

ApplicationDbContext.OnModelCreating() in .Net Standard 2.0 has MissingMethodException

Tag : chash , By : PPD
Date : March 29 2020, 07:55 AM
I wish this helpful for you So, I have a solution for my problem:
use Microsoft.EntityFrameworkCore.SqlServer version 2.2.6 (NOT 3.1.1 even though its supposed to work with .net standard 2.0...)
Related Posts Related QUESTIONS :
  • how to connect mysql8.0 with C#
  • Passing incorrect values into MultiValueConverter by MultiBinding
  • Can i use IEnumerator as Update func?
  • How to convert API Json response to C# Array?
  • Blazor Textfield Oninput User Typing Delay
  • Performing both layout and render transform results in wrong output
  • uwp beforetextchanged cursor moving in front of text
  • How to keep duplicates from a string[] exclude words from a List and print them out
  • .Net Core Strings.Asc/Mid/Chr/Len missing even after importing Microsoft.VisualBasic
  • How to return to previous search page without being asked to Confirm Form Re-submission and keeping the results on ASP.N
  • How set a identity scaffolding item/page how initial page in asp.net MVC core?
  • LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
  • What is "ByteArray.uncompress()" in AS3 equivalent to in C#?
  • Getting a specific letter from a string variable for my simple guessing game for clues
  • Send an email with Outlook without a subject --- dialog box issue
  • passing List<MyModel> from my controller in the "WebInterfaceProject" to the processor method in "D
  • How to convert Word document created from template by OpenXML into MemoryStream?
  • How can I make a single slider that changes the color of an object?
  • Remap JSON parameter in c#
  • What is the difference between "this ref" and "ref this" when talking about C# 7.2 ref extension met
  • Convert OpenSSL encryption into native C#
  • Accessing Properties in Razor Pages
  • How to get SOAP element value
  • Projection after Group
  • C# error cannot convert sytem.text.regularexpressions.match to string
  • Issues with Save/Load System in a Text Based Adventure game made with ScriptableObjects in Unity
  • VS2019 MSBuild.exe - ASP .Net MVC project fails to publish when using PublishProfile, but works when using OutDir parame
  • Does <pages validateRequest="false" /> in Web.config still matter?
  • How to send new request to redirect URL with new access token
  • Attempt to invoke virtual method on a null object reference Xamarin LockScreen
  • "The attribute names could not be inferred from bind attribute 'bind-value'" exception in Blazor
  • How to fix ''System.ArgumentException" in c#?
  • C#. Ref returning delegate for ref extension method
  • Swashbuckle Swagger generate an actual guid
  • Trying to make thousands of database calls simultaneously - they stack instead of running concurently
  • run mstest from cmd using testcontainer
  • How to make M:N (many-to-many) relationship where both M and N are the same entities?
  • Consume COM DLL from multiple clients
  • Convert json string response representing UCHAR array to Byte array
  • Why does this LinqPad program produce different results on the second run?
  • ServiceStack how to use MaxLoginAttempts feature
  • What does "late-bound access to the destination object" mean?
  • How to load appsettings.json inside a Static class based on deploy environment so that I can use in other class librarie
  • dynamically add images to view
  • Are static extension methods on User object safe?
  • Process thousands of database calls simultaneously
  • Trying to decrypt a string with public key(not private) using bouncycastle in .net
  • How to retrieve the name of an usb device
  • Query many-to-many related data using Entity Framework Core
  • ASP.NET MVC : how to find the view from a controller?
  • Inconsistent behaviour using Entity Framework for ASP.NET MVC app vs windows service
  • AutoFixture Customize vs Build
  • How to change textbox location at the click of a mouse in live mode?
  • How can I deserialize a XML file without defining the parent node?
  • asp.net core how decrease class coupling
  • ASP.NET Core Razor Pages Routing With parameters
  • String Escaping With $ Interpolation and @ Encoding
  • ConfigurationManager in ASP.NET WebAPI tested with HttpServer
  • Top down shooting in Unity 2D don't work as I want it to
  • Use own redirectUri when the Authentication expires
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com