无法从OWIN Identity表读取数据问题求助
Hey there, let's work through why your query is returning null even though you know the user exists in the shared database. Here are some practical checks to narrow down the issue:
Case sensitivity mismatch
Many databases (like SQL Server with case-sensitive collation) treatjohn@example.comandJohn@Example.comas different values. Try adjusting your query to ignore case first:var user = usercontext.Users .Where(x => x.Username.Equals(Login_.Email, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault();You can also verify your database's collation setting—look for
CI_AS(case-insensitive) vsCS_AS(case-sensitive) on the Username column or the entire table.Entity Framework mapping errors
Double-check that yourDbContextis correctly mapped to the Identity table:- If you renamed the default
AspNetUserstable, make sure you’ve added the[Table("YourCustomTableName")]attribute to yourIdentityUsersubclass, or configured it via Fluent API. - Confirm the
Usernameproperty in your user class maps to the correct column in the database (sometimes teams useEmailas the username column, so you might need to queryx.Email == Login_.Emailinstead).
- If you renamed the default
Wrong connection string
It’s easy to accidentally point yourusercontextto a local test database instead of the shared one. Debug your connection string (print it to the console or debug window) and cross-verify it with the connection details you use to access the shared database directly.DbContext caching interference
Entity Framework caches entities it’s already fetched, which might be returning an outdated null result. Bypass the cache withAsNoTracking()to pull fresh data from the database:var user = usercontext.Users .AsNoTracking() .Where(x => x.Username == Login_.Email) .FirstOrDefault();Soft-deleted or inactive users
If your application uses soft deletion (e.g., anIsDeletedflag) or user status flags (likeIsActive), make sure your query isn’t filtering out the existing user. Add a check like&& !x.IsDeletedif applicable.Raw SQL sanity check
Run the equivalent SQL query directly against the database (using SSMS, pgAdmin, etc.) to confirm the user exists:SELECT * FROM AspNetUsers WHERE Username = 'your-login-email-here';If this returns the user but your EF query doesn’t, the problem is definitely in your EF configuration. If it doesn’t return the user, the registration process might not have saved the user correctly to the shared database.
Start with these steps—they cover most of the common gotchas with Identity user queries. Let me know if you hit a wall with any of these!
内容的提问来源于stack exchange,提问作者John Nyingi

