You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fix: Use reference equality for transaction sharing detection
PROBLEM:
--------
The original CanShareTransaction() implementation used CONNECTION STRING comparison
to determine if contexts could share transactions. This was fundamentally incorrect
because EF Core's UseTransaction() requires the SAME DbConnection OBJECT INSTANCE
(reference equality), not just matching connection strings.
Each call to .UseSqlServer(connectionString) creates a NEW DbConnection object, so:
- Two contexts with identical connection strings had DIFFERENT connection objects
- String comparison returned TRUE (same strings)
- UseTransaction() would fail or behave unpredictably (different objects)
WHY THIS MATTERS:
-----------------
EF Core's UseTransaction(DbTransaction) method requires that the DbTransaction be
associated with the SAME physical DbConnection that all contexts use. Reference
equality is required - the database cannot coordinate transactions across separate
connection objects even if they connect to the same database.
SOLUTION:
---------
1. Changed CanShareTransaction() from string comparison to reference equality check:
OLD: return connection?.ConnectionString == firstConnectionString;
NEW: return ReferenceEquals(connection, firstConnection);
2. Updated ALL documentation to show correct pattern:
- Users MUST create ONE DbConnection object
- Pass SAME connection instance to all contexts
- Connection lifetime is user's responsibility
3. Added XML documentation explaining reference equality requirement
4. Updated context factory pattern to store and reuse connection object
5. Added connection lifetime management guidance
IMPACT:
-------
This is a design correction made BEFORE PR casbin-net#85 merges to upstream, so there is
NO breaking change to released code. The PR documentation and implementation are
being corrected to reflect EF Core's actual requirements.
Users following the corrected pattern will get reliable atomic transactions.
Users who need separate databases will get predictable non-atomic behavior.
FILES CHANGED:
--------------
- EFCoreAdapter.cs: CanShareTransaction() now uses ReferenceEquals()
- MULTI_CONTEXT_USAGE_GUIDE.md: All examples show shared connection object pattern
- MULTI_CONTEXT_DESIGN.md: Detection logic updated to explain reference equality
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
0 commit comments