My Domain
layer contains below model:
public class ApiResource
{
public bool Enabled { get; set; } = true;
public string Name { get; set; }
public string ClientId { get; set; }
public IEnumerable<string> HandledScopes { get; set; } = Array.Empty<string>();
}
Later, the Infrastructure
layer uses EntityFramework Core
. And it's entity for it:
public class ApiResource
{
public int Id { get; set; }
public bool Enabled { get; set; }
public string Name { get; set; }
public Client Client { get; set; }
public int ClientId { get; set; }
public ICollection<Scope> Scopes { get; set; }
}
Notice that the string ClientId
from model is different from int ClientId
in entity. The second property (in entity) is foreign key to Client
, whereas the string ClientId
is client identifier in "logical sense", used in business logic. They are not the same.
The problem is that if I want to e.g. create new record in database, then I have to convert my model to entity. (At some IRepository
in or something like it in Infrastructure
layer). But I cant do it properly, because the model doesn't know about primary keys. So every time I want to create entity, I have to SELECT
existing relationships from database and then add them to entity instance that I want to create.
Another problem is that if I wouldn't have some identifier in model (in Domain
layer definition), then I even wouldn't know which entity shall I e.g. update.
But that's not the end of problems this approach causes. If I want to select e.g. only Name
from very complex object, I still must have SELECT
whole entity from database. Only thing I can do is to define new methods e.g. in IRepository
for every use case. So if I want to get name, I would have method FindName
etc. It doesn't seem good.
So how would you design Domain
models to be easy implementable and flexible in different databases (relational and no relational), using ORM's like EF or any other? Could you provide any examples?
Domain
layer have to contain models that will be used in logic. But later (in my case) it creates some problems I described in question. So I think I'm doing something wrong.If I want to select e.g. only Name from very complex object I still must have SELECT whole entity
DDD is all about this. You no longer can mutilate data and access to it arbitrarily. You have to get it from the domain model (in memory model) an it should be always be in a valid state. So, in DDD, there's not such a thing asI want to fetch 1/4 of a domain model only
. For the APP the only source of trust is the domain layer, not the data access layer