CQRS DDD - Commands and Domain Models relationship - c#

I'm practicing to implement a project using CQRS and DDD to the best I can and have come up with a question once building the commands.
Scenario: The user sends a command to create a bookshelf in the system which itself could also contain a collection of books.
The command looks like this:
public class CreateNewBookShelfCommand : ICommand
{
public long CommandInitiatorId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<Book> Books { get; set; }
}
All of the Commands reside in the Contracts project that itself is inside the Application solution folder.
The Model project residing in the Domain solution folder hosts the BookShelf entity class which includes a collection of Books.
Questions 1: The command above has this Books property which is of type Book. My question is: should the Commands project directly reference the Model project so that the Book data type would be resolved in the CreateNewBookShelfCommand? Myself, I don't think that the Contracts are allowed to reference any project other than the CommandHandlers or anything else which might be Cross Cutting.
Question 2: So, is this a good practice to replicate part of the Book entity class here at the Contracts project and utilize it in the CreateNewBookShelfCommand?
And this is the Model project I have for Book and BookShelf:
public class BookShelf : BaseEntity
{
public string Name { get; set; }
public string Description { get; set; }
public BookShelfAccess Access { get; set; }
public virtual BookShelfOwner Owner { get; set; }
public long OwnerId { get; set; }
public ICollection<Book> Books { get; set; }
}
public class Book : BaseEntity
{
public string Name { get; set; }
public DateTime? PublishedAt { get; set; }
public int NumberOfPublishes { get; set; }
public virtual BookShelf Shelf { get; set; }
public long ShelfId { get; set; }
}
I hope my explanation has been enough if there is any other information I should add here let me know.

Typically, you would not use the entities in your domain model as elements of your command.
Commands are fundamentally messages, and as such they really ought to be immutable. You want to know that what is received is the same thing that was sent. In DDD terms, you might think of the messages as being value objects.
It doen't make sense to use an entity from your domain model as part of the in memory representation of your command, because you should never be invoking any of the entity methods that change its state.
Commands are much closer in nature to data transfer objects than they are to domain model entities.
Normally, all of the entity objects in your system should live behind an aggregate root interface, and the arguments that you pass to that interface are values. If the domain model needs an entity, it can create one from the values provided.

Related

Data annotations on models when there are multiple repository implementations

My DTOs are pretty simple classes.
public class PlainClass {
public int Id { get; set; }
public string Name { get; set; }
public List<PlainSubClass> SubObjects { get; set; }
}
public class PlainSubClass {
public int Id { get; set; }
public string Name { get; set; }
}
I have a repository interface, whose implementations are meant to retrieve data.
public interface IRepository
{
IEnumerable<PlainClass> PlainObjects { get; }
}
Now, I want to implement that interface in another class mocking the database and also using EF SQLite, and possibly more in the future. My mock is simple but, in trying to implement and then generate the database I'm getting an error back stating I need to designate a primary key.
Now, how should I go about doing that? Should I build out interfaces for my models and add annotations specific to each implementation? Should I -- if it's even possible -- add multiple sets of annotations to the models?

Model and partial model, how to avoid the redundant code?

I have a model and a partial model which contains only the properties that I need to expose in JSON.
But the properties between the model and his partial model are redundant.
How can I avoid that or improve my approach?
namespace Dashboard.Models.UserModels
{
public class UserModel
{
public int id { get; set; }
public string dbName { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
public int idExternal { get; set; }
public int idInstance { get; set; }
public string login { get; set; }
public string password { get; set; }
public DateTime? dtContractStart { get; set; }
public DateTime? dtContractEnd { get; set; }
public string emailPro { get; set; }
public string emailPerso { get; set; }
public LuccaUserModel()
{
idInstance = -1;
}
// partial model for json result
// not sure is the best way or have to be here
public class PartialUserModel
{
public int id { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
public string emailPro { get; set; }
public string emailPerso { get; set; }
public DateTime? dtContractStart { get; set; }
public DateTime? dtContractEnd { get; set; }
public string url { get; set; }
}
// UserModel Methods
}
}
You can rename PartialUserModel UserModelBase class (or leave it as is... it just makes better logical sense to do so) and make UserModel to inherit from it:
public class UserModel : UserModelBase
{
...
}
Of course you'll need to remove all duplicate properties from UserModel in this case.
It's a thin line between doing a proper design and building an overkill design. Answer depends on many inputs, among which I chose to have project and model breadth most important.
In hope to have my answer clearer, I have to say I use different terminology. Data which is adopted for use in UI is usually called ViewModel. In your case, you would build UserViewModel which contains necessary subset of information.
If I'm working on a one-off project, I'll reuse model as a ViewModel. I'll do this by having helper method which removes sensitive information, loads up or cuts off data which is lazy loaded from database and does other preparation on data. All this is done with same model class.
If it's not a short term project, I look to create separate ViewModel classes which I map from model data. Then, if I'm working with mostly flat data I use AutoMapper tool to have data automatically copied, instead of writing my own mappers.
As another answer here states, you write a basic class with data you need in UI and extend it with other model data, however this is not a good approach for several reasons.
If violates separation of concerns. Project dealing with model and persistance should not know about your ViewModel
You may need to flatten data from related objects into ViewModel objects. In that case, your model objects would have fields which should not be there, or would be redundant.
You may need calculated fields and helper methods in ViewModel which would again end up in model, confusing everyone that is not updated about design.
You could want to adopt several unrelated model classes to same ViewModel class
To try and put it shortly, either reuse model class or create ViewModels. There is unfortunately no clever solution. If you find one, please post a comment as I'd like to hear about it :)

Which one is better as POCO model property: ForeignKey/ID or Object reference?

Hi I am starting using EF 4.1 and POCO in the project I am working on. The model I am using looks like this:
public class Contact1
{
// Primary key
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Address DelAddress { get; set; }
public virtual Address POAddress { get; set; }
public string EmailAddress { get; set; }
public bool InActive { get; set; }
public string Comment { get; set; }
public string Phone1 { get; set; }
public string Phone2 { get; set; }
}
But I did see quite a few examples using ForeignID as a reference for field such as Address and I am using a directly reference to an Address Object in my Model. I think using reference is better because I am dealing with Objects at this level but not records or DB level which will end up referenced by an ID anyway. But still, what would you use for your Code First Model?
Assuming all other things are equal, object references are better because the "noise" of "soft" ID-based references pollute your model.
That said, all other thing's aren't equal as Ladislav writes in Foreign key vs. Independent associations in EF 4. For example, independent associations require you have both ends of the relationship in memory. This can be a bit problematic when saving updates in that you have to load the target of a relationship when you otherwise wouldn't in order for it to be in the ObjectStateManager. This is a particular pain when saving an entity that has many reference to "reference data" type entities and when working in an N-tier architecture.
Both work mostly ok but their implementations aren't complete and don't have parity. So better can't be answered with complete certainty without a more rigorous analysis your usage patterns, architecture, and performance requirements.

How to create a DTO in asp.net?

1) I want to know what is the recommended way to create & return a DTO for an object which has 10 attributes and I only want to return 2 with my DTO object.
2) Should DTO's have their own namespace ? If yes, how do we organize them ? Each DTO inside a single class file or all DTO's inside a single class ?
Please provide me some sample code.
DTOs are dumb objects composed of public getters/setters. I generally put them in a separate namespace called SomeProject.Dto.
public class CustomerDto {
public int Id { get; set; }
public string Name { get; set; }
public LocationDto HomeAddress { get; set; }
}
I generally try to keep the property names the same between the DTO and corresponding domain class, possibly with some flattening. For example, my Customer might have an Address object, but my DTO might have that flattened to:
public class CustomerDto {
public int Id { get; set; }
public string Name { get; set; }
public string HomeStreet { get; set; }
public string HomeCity { get; set; }
public string HomeProvince { get; set; }
public string HomeCountry { get; set; }
public string HomePostalCode { get; set; }
}
You can dramatically reduce the amount of repetitive mapping code of translating domain objects into DTOs by using Jimmy Bogard's AutoMapper.
http://automapper.codeplex.com/
Your question is very open ended. The answers are dependent on the scale of your application.
In general I create my DTO's or ViewModels in their own assembly. To get my DTO's I have some service layer take care of creating them based on my request.
If you want concrete examples take a look at some of the Asp.NET MVC examples at asp.net. While you may not be using MVC you can at least see how the ViewModels are created.

DTO shape: flat, complex/nested, or a mixture of both

I have an MVC2 n-tier application (DAL, Domain, Service, MVC web) using a DDD approach (Domain Driven Design), having a Domain Model with repositories. My service layer uses a Request/Response pattern, in which the Request and Response objects contain DTO's (Data Transfer Objects) to marshal data from one layer to the next, and the mapping is done via help from AutoMapper. My question is this: what shape should a DTO typically take? Can it have nested/complex DTO's as well or should it strictly be a flat projection? Or possibly a mixture of both? Also, what are the main reasons for having a flat DTO vs a more complex/nested DTO?
For instance, suppose I had a domain such as the following:
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Company Company { get; set; }
}
public class Company
{
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
There are three different ways I've thought of modeling the Response object.
Option 1 - the DRYest option:
public class GetEmployeeResponse
{
public class EmployeeDTO { get; set; } // contains a CompanyDTO property
}
From the research I've done, it would be inappropriate for a DTO to take a similar shape as the domain object(s) as demonstrated above.
Option 2 - a flattened projection of the domain (anti-DRY):
public class GetEmployeeResponse
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
public string CompanyCity { get; set; }
public string CompanyState { get; set; }
}
This is more simple, like a DTO apparently should be, but ultimately makes for more DTOs.
Option 3 - a mixture of both:
public class GetEmployeeResponse
{
public EmployeeDTO Employee { get; set; }
public CompanyDTO Company { get; set; }
}
This allows for the code to be a little bit more dry, reusable and manageable, and doesn't expose my domain structure to the end user. The other main benefit is that other responses, like GetCompanyResponse could simply return CompanyDTO, without having to make a copy of all those properties, similar to option 2. What do you think? Which option of these (if any) have you taken and/or have worked for you? If these Request/Responses later get exposed as WCF service methods, does your answer change?
My personal preference would be to try and keep it flat as possible with only the required data being transfered. having said that I have used deeply nested DTO in the past because it made sense at the time and fitted the requirements. so I guess it comes down to "it depends". At the end of the day go with what makes sense for the application at hand. No point trying to shoe horn data into a DTO convention that doesn't fit what you are tying to achieve.

Categories

Resources