jeudi 12 septembre 2019

Can I create and object that "self-loads" properties from a data source?

I have a design pattern question that I'm hoping you can help me with.

I have a C# application that stores objects in a database as JSON. Currently, a dedicated class handles loading the JSON, deserializing, and returning the object. This works great, but I'm wondering if there is an approach that would allow the object to "self-load" (for lack of a better term).

What I am doing now is (short-hand code):

public class MyObject {
    public string Name;
    public string Rank;
    public int SerialNo;
}

public class DataTransport{
   public MyObject LoadMyObject(string ObjectId){
       string ObjectJSON = fetch.from.database;
       return ObjectJSON.deserialize.object;
   }
}

DataTransport dt = new DataTransport();
MyObject mo = dt.LoadMyObject("object123");


What I would like to do is something like:

public class MyObject {
    public string Name;
    public string Rank;
    public int SerialNo;
    public MyObject(string ObjectId){
       DataTransport dt = new DataTransport();
       this = dt.LoadMyObject(ObjectId);
    }
}

MyObject mo = new MyObject("object123);


Obviously this fails, but is there a similar mechanism to have the constructor replace itself with the object loaded from the database?

I've thought about loading and manually assigning properties when instantiated, but that risk and hassle doesn't pass the cost/benefit smell test.

Thanks in advance for your help!

Aucun commentaire:

Enregistrer un commentaire