0

Okay, for a basic example say I have an application with expenses and each expense in my SQL database has an Id, Employee Id and the Amount. Should I do this:

public class Expense
{
    public int Id { get; set; }
    public Employee Employee { get; set; }
    public decimal Amount { get; set; }
}

Or This:

public class Expense
{
    public int Id { get; set; }
    public int EmployeeId { get; set; }
    public decimal Amount { get; set; }
}

You see I would normally do the first and when I fetch an expense from the database I would set the Employee field by calling a constructor like: Employee = new Employee(int id) this would then make another trip to the DB to complete the members in the Employee object. This is handy because now I can access the Employees members/functions via the expense.. I.E. if I bound as a ObjectDataSource I could display something like Eval("Employee.Name") and show something more friendly then just a number as it is stored in the DB.

However the current project I'm working on may run up 10's of thousands of rows and the number of DB requests is going to sky rocket if i'm fetching first expense details and then employee details for each object. (and in fact my current project has a table with 6-7 foreign keys).

Is there some way of having my cake and eating it too?

Maybe by having an interface class only with Id fields and not the full object fields? but I feel like I've never fully understood Interfaces so I'm not sure if that would make a difference.

Thanks to anyone who has read this far even if you don't have any answer for me.

1
  • 2
    Seems like an object relational framework with the use of LazyLoading is pretty near to 'best-of-both-worlds'. May 8, 2013 at 17:46

2 Answers 2

3

It depends: If you are using a feature-rich ORM (NHibernate) that can handle things like relations cleanly then 1st code would be more convenient; or if these are your View Model objects you can delegate this task to a DI engine (like Ninject).

If the design of your app demands more control on how objects come and go or if you use Expense heavily (Not the Employee) you should use 2nd design (of course i.e. NHibernate has a sophisticated caching toolbox that can be employed to implement this).

0

Seems to me that your second example would not prevent you from getting both the expense and the employee in a dataset. On the other hand, I would guess that you can have many expenses for one empoyee, so if you fetch 1000 expenses that are related to 100 employees then you have 1000 employee objects floating around with 900 of them being dead weight. How you represent them in classes does not necessarily change how you represent them in a database.

Not the answer you're looking for? Browse other questions tagged or ask your own question.