I’m new to creating objects and such in C# (winforms) and need to know the best approach to this. I’ve got a simple object that will return some data from our database. Normally, I would put the DS string (encoded) in the object and be done but the issue I’ve found with that is this doesn’t make the object truely “mobile” to be able to be used in any of our applications (web or windows). So, is it best to create an object that requires the encoded db string in the constructor or how should I go about doing it?
Here’s what I was thinking:
public class foo
{
public foo(string EncodedConnectionString)
{
_EncodedConnectionString = EncodedConnectionString;
}
private string _EncodedConnectionString { get; set; }
private DataSet GetFooFromDB()
{
oDatabase = new SQLDataBase(
EncodedConnectionString, 15);
//remaining code omitted...
}
}
Thoughts, comments?
Actually, the objects themselves should be agnostic when it comes to persistence. What I mean by that is that the objects should neither care nor even be aware of how they are being stored/loaded.
There are multiple ways to accomplish persistence. One way is to have a DAL (Data Access Layer) which knows how to load and store the data associated with your objects. Bear in mind though, that even the DAL won’t have the connection string hard coded but rather should pull it from your config file as necessary.
A simple example is here: http://www.radsoftware.com.au/articles/dataaccesslayerdesign1.aspx Personally, I don’t agree with everything on how that was done, but it’s a good starting point to learn about them.
For a little more advanced reading look at the Entity Framework http://msdn.microsoft.com/en-us/library/bb399572.aspx
Another way is to use Inversion of Control and Dependency Injection. The idea being that your object would have
Save()andLoad()methods which accepted some type of interface that performed the actual persistence. http://msdn.microsoft.com/en-us/library/aa973811.aspxThis is a bit more complicated to get your head around but pays dividends with the flexibility to swap out repositories on demand. Meaning that it is much simpler to support multiple database backends or even storing the objects in csv / xml files.