Skip to content

Fix Entity.SaveAsync method session queue issue with sharding - #70

Merged
nnhy merged 1 commit into
masterfrom
copilot/fix-69
Sep 18, 2025
Merged

nnhy merged 1 commit into
masterfrom
copilot/fix-69

Conversation

Copilot AI commented Sep 18, 2025 •

Copy link
Copy Markdown
Contributor

The SaveAsync method in Entity<TEntity> had a critical bug when using database sharding (分表分库). The method was obtaining a reference to the session queue before creating the shard, but creating the shard changes the session context, making the queue reference stale.

Problem

// Before fix - problematic code:
var queue = Meta.Session.Queue;           // Gets queue from current session
queue.InsertOnly = Meta.Table.DataTable.InsertOnly;

if (Meta.InShard) return queue.Add(this, msDelay);

// This changes Meta.Session to point to a different session!
using var split = Meta.CreateShard((this as TEntity)!);

return queue.Add(this, msDelay);          // Still uses old queue!

When Meta.CreateShard() is called, it modifies Meta.ConnName and Meta.TableName, which causes the SessionWrap.Reset() method to nullify the _Session field. Subsequent calls to Meta.Session return a new session instance for the sharded table, but the queue variable still references the queue from the original session.

Solution

The fix restructures the queue acquisition to ensure the correct session queue is used:

// After fix - correct code:
if (Meta.InShard)
{
    // Already in shard context, use current queue
    var queue = Meta.Session.Queue;
    queue.InsertOnly = Meta.Table.DataTable.InsertOnly;
    return queue.Add(this, msDelay);
}

// Create shard first, then get the correct queue
using var split = Meta.CreateShard((this as TEntity)!);

// Now get queue from the updated session
var queue2 = Meta.Session.Queue;
queue2.InsertOnly = Meta.Table.DataTable.InsertOnly;
return queue2.Add(this, msDelay);

This ensures that entities are properly queued to the correct session when using sharding functionality, preventing data from being saved to the wrong database or table.

Fixes #69.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

@nnhy
nnhy marked this pull request as ready for review September 18, 2025 14:17
@nnhy
nnhy merged commit 8cba725 into master Sep 18, 2025
1 check passed
Copilot AI changed the title [WIP] Entity.SaveAsync 方法异常 Fix Entity.SaveAsync method session queue issue with sharding Sep 18, 2025
Copilot AI requested a review from nnhy September 18, 2025 14:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Entity.SaveAsync 方法异常

2 participants