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

c# - Save MongoDB Database Object on Modify

问题描述:

I have a number of Objects I've created that I use Globally in my Application. I would like them to be saved when a Property under them is modified.

Would something like this work? Wouldn't this only save it if I was actually setting a new value of Campaign, not accessing something under it like Campaign.Name?

public Campaign Campaign

{

get { return _campaign; }

set { SaveCampaign(value); }

}

private static void SaveCampaign(Campaign campaign)

{

var databaseClient = new MongoClient(TerminusService.DatabaseConnectionString);

var server = databaseClient.GetServer();

var database = server.GetDatabase("TerminusDialer");

var collection = database.GetCollection<Campaign>("campaigns");

collection.Save(campaign);

}

网友答案:

Yes, this will only save if you're setting a new value to Campaign, and not changing its name.

I have a suggestion you could try:

  1. You could create an event which fires whenever a property from that class changes. Here's a compact example: Watch it working on .net fiddle

    class ListenToMe
    {
        public event EventHandler OnPropertyChanged;
    
        private string _name;
        public string Name
        {
            get{return _name;}
            set
            {
                if (_name!=value)
                {
                    this._name = value;
                    OnPropertyChanged(this,new EventArgs());
                }
            }
        }
    }
    
    public static void Main()
    {
        ListenToMe someone = new ListenToMe();
        someone.OnPropertyChanged += (o,e) => Console.WriteLine("My new name is: "+ someone.Name); // we will do something whenever props change
        someone.Name = "Mary"; // upon changing it, it appears on Console
        someone.Name = "Lucy";
        someone.Name = "Angelica";
    }
    

You'll see a lot of information about this kind of approach if you look around for the interface INotifyPropertyChanged, which is largely used to bind UI elements to the view model (and for other things as well).

You could also just call a method from each set for each property of the class, but then you'd have to call the method from Campaign, which might be undesirable. That's why publishing an event seem nicer in these circunstances.

Note: Also, as a word of advice, be careful when doing this kind of thing. I believe you're doing this to "auto-save" information at each step, and it seems interesting, but you may end up making lots of roundtrips to your database during certain operations if you forget that each property set will cause a db update side-effect.

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