vkhorikov / DddAndEFCore

Source code for the DDD and EF Core Pluralsight course
https://enterprisecraftsmanship.com/ps-ef-core
MIT License
249 stars 90 forks source link

Raising events while creating entity #4

Closed iTKerry closed 3 years ago

iTKerry commented 3 years ago

Problem

I'm trying to understand of how to raise event while creating entity. For example, you have next line: RaiseDomainEvent(new StudentEmailChangedEvent(Id, email)); This will raise domain event for existing entity with it unique identifier.

Is it possible to do the same, but for entities that wasn't stored to DB? Lets say, I want to know when entity was created and for some reason I need his identifier. Probably attach ID at overload of SaveChanges method, or something like that. Which way is correct from DDD perspective for that simple task?

Thanks!

vkhorikov commented 3 years ago

Good question, and I should've mentioned this in the course. The more appropriate way to raise events would be by passing them a student instance, not the student id. In fact, the passing of the Id contradicts the guideline I mentioned in the course: that you shouldn't use Ids in the domain layer (which domain events are part of).

So:

iTKerry commented 3 years ago

Thanks for your answer. I just tried and it works like a charm!