DDD and entity base, a model using several types of identities

I have a model that looks like this:

public interface IEntity { int Id { get; set; } } 

Then the idea is for my objects to 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 objects to inherit the same interface, but this would force me to add an integer column with a user id in UserSession, which is not needed, since Guid is an identifier, but it will save the domain model well, since all objects inherit from the same base.

What options do I have in this scenario? Can I have two basic interfaces: one for int and one for Guid? Should I add an identifier column to the UserSession element, although it is not needed? I need a Guid, so I can’t just get rid of it and replace it with an integer.

Any thoughts on best practices?

+4
source share
3 answers

You can implement the same IEntity interface in all of your entities and still have a different type in each Id field.

Enter Generics ..

Define your interface as follows.

 public interface IEntity<T> { T Id { get; set; } } 

The implementation of the interface in your essence.

 public class User : IEntity<int> { public int Id { get; set; } } public class UserSession : IEntity<Guid> { public Guid Id { get; set; } } 
+3
source

try it

 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; } } } 
+1
source

Always use Guid to identify an object.

Guides have significant advantages over the fact that they can be generated on the client, which frees you from batch commands, displays the result of insertion in AJAX without asking for an identifier, etc.

0
source

Source: https://habr.com/ru/post/1308667/


All Articles