Skip to content

Instantly share code, notes, and snippets.

@AlexZeitler
Last active October 13, 2022 07:14
Show Gist options
  • Save AlexZeitler/3a07112da9652a05f350e94e4c916660 to your computer and use it in GitHub Desktop.
Save AlexZeitler/3a07112da9652a05f350e94e4c916660 to your computer and use it in GitHub Desktop.
MartenDb projections
public abstract class AppUser
{
public Guid Id { get; set; }
}
public class RegisteredUser : AppUser
{
public void Apply(Registered registered)
{
Username = registered.Username;
}
// remove this projection when user is disabled
internal bool ShouldDelete(Disabled _) => true;
public string Username { get; set; }
}
public class DisabledUser : AppUser
{
// start this projection when user is disabled
public void Apply(Disabled disabled)
{
UserName = disabled.Username
}
public string Username { get; set; }
}
services.AddMarten(options =>
{
options.Schema.For<AppUser>()
.AddSubClass<RegisteredUser>()
.AddSubClass<DisabledUser>();
});
// register user, then disable it as both events are on the same stream
var registered = new Registered(username);
var disabled = new Disabled(username);
// store events
session.Events.StartStream<AppUser>(streamId, registered, disabled);
await session.SaveChangesAsync();
var user = session.Load<AppUser>(streamId); // (AppUser is DisabledUser)-> true
var users = session.Query<AppUser>().ToList(); // Count -> 1
var registeredUser = session.Load<RegisteredUser>(streamId); // -> null
var disabledUser = session.Load<DisabledUser>(streamId); // -> not null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment