Caching Patterns in ASP.NET

后端 未结 3 1902
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 18:51

So I just fixed a bug in a framework I\'m developing. The pseudo-pseudocode looks like this:

myoldObject = new MyObject { someValue = \"old value\" };
cache.Inse         


        
相关标签:
3条回答
  • 2021-01-30 19:08

    Dirty tracking is the normal way to handle this, I think. Something like:

    class MyObject {
      public string SomeValue { 
         get { return _someValue; }
         set { 
           if (value != SomeValue) {
              IsDirty = true;
              _someValue = value;
           }
      }
    
      public bool IsDirty {
         get;
         private set;
      }
    
      void SaveToDatabase() {
         base.SaveToDatabase(); 
         IsDirty = false;
      }
    }
    
    myoldObject = new MyObject { someValue = "old value" };
    cache.Insert("myObjectKey", myoldObject);
    myNewObject = cache.Get("myObjectKey");
    myNewObject.someValue = "new value";
    if(myNewObject.IsDirty)
       myNewObject.SaveToDatabase();
    
    0 讨论(0)
  • 2021-01-30 19:12

    A little improvement on Marks anwser when using linq:

    When using Linq, fetching entities from DB will mark every object as IsDirty. I made a workaround for this, by not setting IsDirty when the value is not set; for this instance: when null. For ints, I sat the orig-value to -1, and then checked for that. This will not work, however, if the saved value is the same as the uninitialized value (null in my example).

    private string _name;
    [Column]
    public string Name
    {
        get { return _name; }
        set
        {
            if (value != _name)
            {
                if (_name != null)
                {
                    IsDirty = true;   
                }
                _name = value;
            }
        }
    }
    

    Could probably be improved further by setting IsDirty after initialization somehow.

    0 讨论(0)
  • 2021-01-30 19:29

    I've done similar things, but I got around it by cloning too. The difference is that I had the cache do the cloning. When you put an object into the cache, the cache will clone the object first and store the cloned version (so you can mutate the original object without poisoning the cache). When you get an object from the cache, the cache returns a clone of the object instead of the stored object (again so that the caller can mutate the object without effecting the cached/canonical object).

    I think that this is perfectly acceptable as long as the data you're storing/duping is small.

    0 讨论(0)
提交回复
热议问题