当前位置: 动力学知识库 > 问答 > 编程问答 >

entity framework 4 - Returning Updated Results from DBSet.SqlQuery

问题描述:

I want to use the following method to flag people in the Person table so that they can be processed. These people must be flagged as "In Process" so that other threads do not operate on the same rows.

In SQL Management Studio the query works as expected. When I call the method in my application I receive the row for the person but with the old status.

Status is one of many navigation properties off of Person and when this query returns it is the only property returned as a proxy object.

// This is how I'm calling it (obvious, I know)

var result = PersonLogic.GetPeopleWaitingInLine(100);

// And Here is my method.

public IList<Person> GetPeopleWaitingInLine(int count)

{

const string query =

@"UPDATE top(@count) PERSON

SET PERSON_STATUS_ID = @inProcessStatusId

OUTPUT INSERTED.PERSON_ID,

INSERTED.STATUS_ID

FROM PERSON

WHERE PERSON_STATUS_ID = @queuedStatusId";

var queuedStatusId = StatusLogic.GetStatus("Queued").Id;

var inProcessStatusId = StatusLogic.GetStatus("In Process").Id;

return Context.People.SqlQuery(query,

new SqlParameter("count", count),

new SqlParameter("queuedStateId", queuedStateId),

new SqlParameter("inProcessStateId", inProcessStateId)

}

// update | if I refresh the result set then I get the correct results

// but I'm not sure about this solution since it will require 2 DB calls

Context.ObjectContext().Refresh(RefreshMode.StoreWins, results);

网友答案:

I know it is an old question but this could help somebody.

It seems you are using a global Context for your query, EF is designed to retain cache info, if you allways need fresh data must use a fresh context to retrieve it. as this:

using (var tmpContext = new Contex())
{
    // your query here
} 

This create the context and recycle it. This means no cache was stored and next time it gets fresh data from database not from cache.

分享给朋友:
您可能感兴趣的文章:
随机阅读: