Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the ID in the business object be read-only or not?

In my mind the ID field of a business object should be read-only (public get and private set) as by definition the ID will never change (as it uniquely identifies a record in the database).

This creates a problem when you create a new object (ID not set yet), save it in the database through a stored procedure for example which returns the newly created ID then how do you store it back in the object if the ID property is read-only?

Example:

Employee employee = new Employee();  
employee.FirstName="John";  
employee.LastName="Smith";  

EmployeeDAL.Save(employee);

How does the Save method (which actually connects to the database to save the new employee) update the EmployeeId property in the Employee object if this property is read-only (which should be as the EmployeeId will never ever change once it's created).

It looks like the Id should be writable by the DAL and read-only for the rest of the world. How do you implement this especially if the DAL classes and the Business object ones are in different assemblies?

I don't want to create a Save method in the Employee class as this class should have nothing to do with the database.

like image 527
Anthony Avatar asked Aug 11 '09 10:08

Anthony


1 Answers

Another possible solution is to declare Employee as :-

public class Employee
{
    public int Id { get; internal set; }
}

... provided that the Employee and DAL classes are in the same assembly

I don't claim to like it but I have used it.

like image 90
MikeJ-UK Avatar answered Sep 22 '22 06:09

MikeJ-UK