Entity Framework: Entity is cached when update and

2019-08-07 18:45发布

问题:

I'm using EF4 with Visual Studio 2010 and SQL Server 2008 R2.

I am selecting an entity. After that I call a stored procedure which updates that entity en reselects it from the database. When I catch the result of the stored procedure in code, I see that the old (previously selected) properties.

Obviously I'm looking at the cached entity value. Is there a way to signal EF that my entity was updated? Or a magic property of some sort?

My database table (and entity) look something like this:

CREATE TABLE [Message]
(
    ID int IDENTITY(1, 1) PRIMARY KEY,
    Content XML,
    StateID int NOT NULL,
)

My SP is something like this:

CREATE PROCEDURE sp_Queue_s
AS
BEGIN
    DECLARE @queue table ([ID] int NOT NULL)
    BEGIN TRAN
        INSERT INTO @queue
        SELECT [ID]
        FROM [Message]
        WHERE   StateID = 1

        UPDATE [Message]
        SET StateID = 2
        WHERE ID IN (SELECT ID FROM @queue)
    COMMIT TRAN
    -- Select the queue
    SELECT [ID], [Content], [Message]
    FROM [Message]
    WHERE [ID] IN (SELECT ID FROM @queue)
END

My C# code looks something like this:

using (var context = new MyEntities())
            {
                int id = 1;
                var message = context.Messages.Single(m => m.ID == id);
                var messages = context.GetQueue(); // Function import of sp_Queue_s, maps on the Message entity
                var messageUpdated = messages.Single(m => m.ID == id);
            }

回答1:

GetQueue should be a generated method internally calling context.ExecuteFunction. ExecuteFunction has multiple overloads and one of them accepts MergeOption. Try to call ExecuteFunction directly with MergeOption.OverwriteChanges.