Reputation: 267
I am attempting to create an application which interacts with a database.
I program in many languages and I loved how easy it was to use Models in an MVC based application.
So my question is, trying to replicate this functionality, I have 2 classes as follows:
Base Class:
public class BaseModel
{
protected string TableName { get; set; }
public BaseModel()
{
}
public void Save()
{
// Save data in derived class to table stored in TableName
}
}
Derived Class:
public class UserModel : BaseModel
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public UserModel()
{
base.TableName = "user";
}
}
From my main application, i want to be able to do the following:
public class Class1
{
public Class1()
{
UserModel model = new UserModel();
model.Field1 = "Value1";
model.Field2 = "Value2";
model.Save();
}
}
Here is where i have hit a problem. I cannot for the life in me figure out, how i would be able to access the properties in UserModel so they can be saved to the database table specified in in the constructor of UserModel to the BaseModel.
Hope this made sense. :)
This code is not my working code, it is a very simple representation of what i would like to achieve so Fields and properties (validators etc) have been dumbed down for ease of reading.
Upvotes: 1
Views: 1677
Reputation: 57262
I think that a more "real" example would actually help understand better, but I think that you should create a virtual (or even abstract) method in the base class to get the data to save in the database:
public class BaseModel {
protected virtual string GetDataToSaveInDB() {
// if it makes sense to have the data as a string...
}
public void Save() {
string data = GetDataToSaveInDB();
// do something with data...
}
}
Then you return the data in the derived classes:
public class UserModel : BaseModel {
protected override string GetDataToSaveInDB() {
return "Field1=" + Field1 + ";Field2=" + Field2;
}
}
This is just to illustrate the concept, if you provide more information it will be easier to provide a real answer.
How do you save the data in your DB? How is the structure to the table?
Upvotes: 1
Reputation: 25505
This is in general solved by utilize abstract functions at the base level and then overriding them with specifics in the derived class. So would would set up a call tree in the base but functions that need to know the details of the derived class would be implemented in the derived class.
public class BaseModel
{
protected string TableName { get; set; }
public BaseModel()
{
}
public abstract void Save();
}
In this case where you have one concrete data representation manifested in a base class it may be better to create a DTO object which your business classes take in a utilize. This is the approch of most of the frameworks like entity.
Upvotes: 0