I've started working for a company that maintains a small/medium sized commercial website. The website is written in c# asp.net, and uses SQL Server as a database. The structure of the code is very messy at the moment (for instance, ~5000 line Utility.cs
file) so I want to move towards a better design on the asp.net side of the application.
I'm trying to figure out the right way to do this. My basic plan is to create a class for every logically distinct item in the application (mostly mapping 1-1 to database tables, but sometimes N-1 or 1-N). Then, I plan to have some static factory methods to instantiate these classes by querying the database. The developer should be able to manipulate the resultant object, and then use a UpdateDatabase()
method to save the changes to the database.
For example, here is how an Email
object would work:
public class Email {
Guid userId;
Guid emailId;
String emailValueInitial = null;
Sting emailValueNew = null;
private Email();
public static Email RetrieveEmail(Guid UserId, Guid EmailId) {
// .. query
return new Email(UserId,EmailId,emailValueInitial);
}
public String EmailValue {
get {
if (emailValueNew == null) return emailValueInitial;
else return emailValueNew;
}
set {
emailValueNew = value;
}
}
public bool Update() {
// .. update database with value of emailValueNew or do nothing if it hasn't
// been changed
}
}
Notes:
- I could update the database whenever a field is changed, but this is obviously inefficient.
- I don't know what to do in the event that the developer wants to insert a
null
value into the database - I suppose I need different concepts for 'null as variable not yet used' vs 'null as database value null'.
The above is a simple case. I'd also need some way of knowing about many-one relationships in tables. For instance, a User could work like this:
public class User {
Guid userId;
public Emails emails = new Emails(userId);
private User(); // etc..
public RetrieveUser();
public CreateUser();
public Update();
}
public class Emails {
List<Email> emails = new List<Email>();
Guid userId;
public Emails(Guid userId); // etc..
public bool CreateEmail(); // its convinient to create/delete from here
public bool DeleteEmail(); // as I can enforce, say, minimum 1 email per user
}
These above are my first thoughts on how to solve this problem, but I've never done anything like this before, and I don't know what problems I might come across. I want to make a system that will be scaleable and easy to develop as we take on more programmers, so its really important to get the initial design correct.
What kind of design should I use in an object-orientated language to best represent and link with a database? What are important things to consider? Is there existing literature on this subject, or important libraries/constructs I have neglected?