Reputation: 1557
We're using MongoDb as a datasource for our application, which is built using cqrs and event sourcing. The problem that we faced today is what is the best way to implement mapping (denormalization) of events to read database. For example, we have a user MongoDb collection which contains all info about user.We have event like this:
[Serializable]
public class PasswordChangedEvent : DomainEvent
{
private string _hashedPassword;
private string _salt;
public PasswordChangedEvent()
{
}
public PasswordChangedEvent(string hashedPassword, string salt, DateTime createdDate)
:base(createdDate)
{
HashedPassword = hashedPassword;
Salt = salt;
}
public string HashedPassword
{
private set { _hashedPassword = value; }
get { return _hashedPassword; }
}
public string Salt
{
private set { _salt = value; }
get { return _salt; }
}
}
And read DTO like
public class User : BaseReportDataObject
{
public string Name { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
public DateTime? BirthDate { get; set; }
public string HashedPassword { get; set; }
public string Salt { get; set; }
public string RestoreHash { get; set; }
public string OpenIdIdentifyer { get; set; }
}
Our current solution for updating documents with events goes like this: we have some mapping code for our events (BsonClassMap.RegisterClassMap etc.) and code for update:
MongoCollection.Update(Query<PasswordChangedEvent>.EQ(ev => ev.AggregateId, evnt.AggregateId),
Update<PasswordChangedEvent>
.Set(ev => ev.HashedPassword, evnt.HashedPassword)
.Set(ev => ev.Salt, evnt.Salt));
The code looks little ugly and redundant to me: with all that lambda stuff we still need to provide property values explicitly. Another way is to replace PasswordChangedEvent with User dto, so we do not need event mapping anymore:
MongoCollection.Update(Query<ReadDto.User>.EQ(u => u.Id, evnt.AggregateId),
Update<ReadDto.User>.Set(u => u.HashedPassword, evnt.HashedPassword));
So the question again: is there any better way to do such a type of mapping? Two types of objects (Events and DTO) mapped to the same mongo db collection.
Upvotes: 3
Views: 1018
Reputation: 957
It seems like this is actually a question about mapping data from one object to another? If so, you may want to consider using something like Ditto or AutoMapper. I am the developer of ditto and have used it for a number of CQRS systems effectively...I wrote it to handle mixing in alot of different objects' data into the same View Model. These are known as OO mappers and typically have some form of bootstrapping configuration code, often using sensible conventions to avoid all the redundancy.
Upvotes: 1