i have this problem modelling one of my entities:
- My entity must have a mandatory ID field that user use to recognize single object
- User don't want to manual enter ID but it must be generate by Application incrementing by 1 every time
- Appllication resides only on clients machine, on server there is only the db
According to 1. I create Id field as mandatory (and not nullable), in this way it must be provided to create an instance but how can program know which ID has to use?
Ideally i have to query db to get max id, add 1 and use this value but how can do it? To mee it seem a matter of my domain object, and i want to isolate domain layer from data access layer so i cant call directly repository from by entity.
Possible solutions:
- I look to Interlocked.Increment but how can use it if any user can create a new instance on his client?
- Move the logic to Application Logic layer: there i can call the repository, get the ID, create the class and call repository to save class. in this way a move a domain logic (the incremental id is a specific user request) out of domain layer
- Define repository interface in Domain Layer, call the interface in constructor method of my entity. All doing with dependecy injection, but how? I use ninject in my bootstrapper and all references goes from top to down, how can i revert it for domain layer making it call a superior layer avoiding service locator antipattern (otherwise a can simply write NinjectKernel.Get() in my ctor)
- i found this article and it's interesting but he use my solution in a bad way (without interface) and don't define the field as mandatory so he can create a new instance withoud specify id
Are there a better solutions?
EDIT
some code to better explain tha case:
Public MyClass {
public int Id{get;set;}
.....
public MyClass(int id){
if(id != null)
this.Id = id;
else
throw (new ArgumentException)
.....
}
}
So i cant do MyClass mc = new MyClass(null);
but i need to have the id before
in Data Access Layer i use NHibernate and have Uow / Repository pattern
after i can get a valid ID a can write
UnitOfWork.MyClassRepository.Add(mc);