I have a model that looks like this:
public interface IEntity
{
int Id { get; set; }
}
Then the idea is to have my entities inherit from this interface:
public class User : IEntity
{
public int Id { get; set; }
}
开发者_开发百科However, one of my entities actually has a Guid as an identifier.
public class UserSession
{
public Guid Id { get; set; }
}
I really would like all my entities inheriting from the same interface but that would force me to add an integer based identity column to the UserSession which is unnecessary since Guid is the identity, but it would keep the domain model nice since all entities would inherit from the same base.
What options do I have in this scenario? Can I have two base interfaces, one for int and one for Guid? Should I add an identity column into the UserSession entity although it is unnecessary? I need the Guid so I can't just get rid of it and replace it with and integer.
Any thoughts on best practices?
You can certainly implement same IEntity interface in all your entities and still have different type in each Id field.
Enter Generics..
define your interface like this.
public interface IEntity<T>
{
T Id { get; set; }
}
Implementing the interface in your entity..
public class User : IEntity<int>
{
public int Id { get; set; }
}
public class UserSession : IEntity<Guid>
{
public Guid Id { get; set; }
}
Try this
public interface IEntity<T>
{
T Id { get; set; }
}
public abstract class BaseEntity<T, U>
{
U _id;
public U Id
{
get { return _id; }
set { _id = value; }
}
}
And then
public class Person : BaseEntity<Person,int>
{
string _firstName;
string _lastName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
or
public class City: BaseEntity<City,Guid>
{
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
Always use a Guid to identify an entity.
Guids have significant advantages over ints in that they can be generated on the client, which frees you up to batch up commands, display the result of an insert in AJAX without querying for the ID, etc.
精彩评论