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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With