Every entity class in my application must implement the following interface:
public interface IEntity<T> {
T Id { get; set; }
}
Almost 100% of the time the type of T will be an int. However I have to deal with cases were the id may be a composite id. E.g. I could have the following implementations:
public class User : IEntity<int> {
public int Id { get; set; }
...
}
public class Site : IEntity<int> {
public int Id { get; set; }
...
}
public class UserSite : IEntity<UserSiteIdentifier> {
public UserSiteIdentifier Id { get; set; }
...
}
// Note: IIdentifier doesn't have any members
public class UserSiteIdentifier : IIdentifier {
public User User { get; set; }
public Site Site { get; set; }
...
public override ToString() {
return User.Id + "|" + Site.Id;
}
}
Now given an entity instance (where the type is unknown) I need to retrieve the id and convert it to a string. I could say:
object entity = ???;
string id;
if (entity is IEntity<int>)
id = ((IEntity<int>)entity).Id.ToString();
else if (entity is IEntity<IIdentifier>)
id = ((IEntity<IIdentifier>)entity).Id.ToString();
But this code doesn’t sit right with me as I have to repeat almost the same code just to handle composite id’s.
I’d appreciate it if someone could show me a cleaner solution. This application is still a prototype and is completely open to suggestions. Thanks
You can introduce
IEntityinterface:There will be some inconvenience while implementing two properties which are supposed to return the same value but this can be overcome by introducing base class
Entity<T>which will hide theobject Idproperty.then your problematic code could be: