开发者

DDD and Entity Base, Model using multiple identity types

开发者 https://www.devze.com 2022-12-28 19:03 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消