How to requery updated values immediately after up

2019-09-14 18:22发布

问题:

As far as I can tell, changes made to the database by the following code to "MySite" are immediate:

  public List<vcData> UpdateDisplayAndUrl(List<vcData> vcDataList)
    {
        foreach (vcData vcData in vcDataList)
        {
            _entities.ExecuteStoreCommand("UPDATE vcData SET DisplayItem = {0}, DisplayUrl = {1} WHERE ID = {2} ", vcData.DisplayItem, vcData.DisplayUrl, vcData.ID);
        }                   
        return GetTableData();
    }

What I would like to do is to immediately return the newly updated records for further processing, essentially, re-query the changes that have just been made:

    public List<vcData> GetTableData()
    {  
        var result = (from td in _entities.vcData
                      where td.SiteID == "MySite" 
                      select td).ToList();
        return result;
    }  

In my controller code, I am trying to do something like:

_currentvcTickerDataList = Repository.UpdateDisplayAndUrl(vcUnupdatedDataList);
//.....do more stuff with _currentvcTickerDataList, which ought to contain updated information, should it not?

PROBLEM: the GetTableData() method does not seem to return the updated values, only the previous (unupdated) values.

I am new to LINQ, entity framework, and MVC, so I'm pretty certain there is something fundamental that I am missing.

回答1:

You need to set the MergeOption to OverwriteChanges before querying. Please go through the MergeOptions explained in msdn to get a clear idea.

public List<vcData> GetTableData()
{
    var currentMergeOption =  _entities.vcData.MergeOption;
    _entities.vcData.MergeOption = MergeOption.OverwriteChanges;

    var result = (from td in _entities.vcData
                  where td.SiteID == "MySite" 
                  select td).ToList();

    //revert the change
    _entities.vcData.MergeOption = currentMergeOption;

    return result;
}