Skip to main content

arolariu.Backend.Common.DDD.Contracts

arolariu.Backend.Common

arolariu.Backend.Common.DDD.Contracts Namespace

Classes

BaseEntity<T> Class

Provides a foundational abstract base class for all domain entities in the system. This class implements common entity characteristics including identity, auditing, and soft deletion capabilities.

public abstract class BaseEntity<T> : arolariu.Backend.Common.DDD.Contracts.IAuditable

Type parameters

T

The type of the entity's primary key. Common types include System.Guid, System.Int32, and System.String. The type must be compatible with the underlying data store's identifier requirements.

Inheritance System.Object 🡒 BaseEntity<T>

Derived
NamedEntity<T>

Implements IAuditable

Example

// Example entity implementation
public class Product : BaseEntity<Guid>
{
public override required Guid id { get; init; } = Guid.NewGuid();
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}

// Usage with audit tracking
var product = new Product
{
Name = "Sample Product",
Price = 29.99m,
CreatedBy = userId
};

Remarks

This base entity follows Domain-Driven Design (DDD) principles and provides essential entity infrastructure:

Identity Management: - Generic primary key support for different identifier types - Immutable identity once set (init-only property) - JSON serialization order control for consistent API responses

Audit Trail: - Automatic creation and modification tracking - User identification for all changes - Update counter for optimistic concurrency scenarios

Soft Deletion: - Logical deletion support to preserve data integrity - Prevents accidental data loss while maintaining referential integrity - Allows for data recovery and audit trail preservation

Data Store Compatibility: - Optimized for Azure Cosmos DB with specific naming conventions - JSON serialization attributes for consistent API representation - Property ordering ensures predictable serialization output

All entities in the system should inherit from this base class to ensure consistent behavior across the entire domain model and maintain audit requirements.

Properties

BaseEntity<T>.CreatedAt Property

Gets the date and time when the entity was originally created. This timestamp is immutable and represents the initial entity creation moment.

public System.DateTimeOffset CreatedAt { get; init; }

Implements CreatedAt

Property Value

System.DateTimeOffset
A System.DateTimeOffset representing the UTC creation timestamp. This value should be set once during entity initialization and never modified.

Remarks

The creation timestamp serves multiple purposes:

  • Audit trail compliance for regulatory requirements
  • Data lifecycle management and archival policies
  • Business analytics and reporting on entity creation patterns
  • Debugging and troubleshooting by providing creation context

This property uses init-only setter to enforce immutability after object construction. The timestamp should always be in UTC to ensure consistency across different time zones and deployment environments.

BaseEntity<T>.CreatedBy Property

Gets the unique identifier of the user or system that created this entity. This provides accountability and traceability for entity creation operations.

public System.Guid CreatedBy { get; init; }

Implements CreatedBy

Property Value

System.Guid
A System.Guid representing the creator's unique identifier. For system-generated entities, this may be a special system identifier. For user-created entities, this should be the authenticated user's identifier.

Remarks

The creator identifier enables:

  • User accountability for audit and compliance purposes
  • Security investigations and access pattern analysis
  • Business intelligence on user productivity and system usage
  • Data ownership and permission management

This property is immutable after entity creation to maintain audit integrity. System processes should use consistent, documented identifiers to distinguish automated actions from user-initiated operations.

BaseEntity<T>.id Property

Gets or initializes the unique identifier for this entity. This property serves as the primary key and must be unique within the entity's context.

public virtual T? id { get; init; }

Property Value

T
The entity's unique identifier of type T. Can be null for new entities that haven't been persisted yet. Once set, the identifier is immutable to maintain entity identity integrity.

Remarks

The identifier property follows specific conventions:

  • Uses lowercase 'id' for Cosmos DB compatibility requirements
  • Marked as virtual to allow derived classes to override with specific initialization logic
  • Ordered first in JSON serialization for consistent API responses
  • Suppresses naming style warnings due to data store constraints

Common identifier types:

  • System.Guid: Recommended for distributed systems and global uniqueness
  • System.Int32: Suitable for sequential, auto-incrementing scenarios
  • System.String: Used for natural keys or external system identifiers

BaseEntity<T>.IsImportant Property

Gets or sets a value indicating whether this entity is marked as important for business operations. This flag enables prioritization, special handling, and enhanced monitoring capabilities.

public bool IsImportant { get; set; }

Implements IsImportant

Property Value

System.Boolean
true if the entity is marked as important; otherwise, false. The specific meaning of "important" is defined by the business domain context.

Remarks

The importance flag supports various business scenarios:

  • Prioritization in processing queues and batch operations
  • Enhanced monitoring and alerting for critical entities
  • Special backup and disaster recovery procedures
  • Performance optimization for high-priority data

The interpretation of this flag depends on the specific business domain:

  • In e-commerce: VIP customers or high-value products
  • In healthcare: Critical patient records or urgent cases
  • In finance: High-value transactions or regulatory submissions
  • In logistics: Priority shipments or time-sensitive deliveries

This property has a public setter to allow business rules to dynamically adjust entity importance based on changing conditions or business requirements.

BaseEntity<T>.IsSoftDeleted Property

Gets a value indicating whether this entity has been logically deleted. Soft deletion preserves data for audit purposes while excluding it from normal operations.

public bool IsSoftDeleted { get; protected set; }

Implements IsSoftDeleted

Property Value

System.Boolean
true if the entity has been logically deleted; otherwise, false. Soft-deleted entities should be excluded from normal business queries and operations.

Remarks

Soft deletion provides several advantages over physical deletion:

  • Preserves referential integrity in complex domain models
  • Maintains complete audit trails for compliance requirements
  • Enables data recovery in case of accidental deletion
  • Supports business rules requiring historical data preservation

Applications should implement query filters to automatically exclude soft-deleted entities from normal operations while preserving access for audit and recovery scenarios. The soft deletion state should be considered when implementing business logic and data access patterns.

BaseEntity<T>.LastUpdatedAt Property

Gets the date and time when the entity was last modified. This timestamp is updated automatically whenever the entity undergoes changes.

public System.DateTimeOffset LastUpdatedAt { get; protected set; }

Implements LastUpdatedAt

Property Value

System.DateTimeOffset
A System.DateTimeOffset representing the UTC timestamp of the most recent modification. Initially set to the creation time and updated with each subsequent change.

Remarks

The last updated timestamp supports:

  • Optimistic concurrency control to prevent conflicting updates
  • Change frequency analysis for performance optimization
  • Data freshness validation for caching and synchronization
  • Audit trail completeness verification

Implementations should update this timestamp whenever any property of the entity changes, ensuring accurate change tracking. The timestamp should always be in UTC for consistency across different environments and time zones.

BaseEntity<T>.LastUpdatedBy Property

Gets the unique identifier of the user or system that last modified this entity. This provides accountability for the most recent changes to the entity.

public System.Guid LastUpdatedBy { get; protected set; }

Implements LastUpdatedBy

Property Value

System.Guid
A System.Guid representing the identifier of the user or system that performed the most recent update operation. Initially set to the creator's identifier.

Remarks

The last updater identifier facilitates:

  • Change attribution for audit and accountability purposes
  • Security monitoring and access pattern analysis
  • Collaborative editing scenarios and conflict resolution
  • Performance analysis of user and system operations

This identifier should be updated whenever the entity is modified, regardless of whether the modification is performed by a user or an automated system process. Consistent identifier management enables accurate audit trails and security monitoring.

BaseEntity<T>.NumberOfUpdates Property

Gets the total number of update operations performed on this entity since creation. This counter provides insights into entity change frequency and system usage patterns.

public int NumberOfUpdates { get; set; }

Implements NumberOfUpdates

Property Value

System.Int32
An integer representing the cumulative count of update operations. Starts at 0 for newly created entities and increments with each modification.

Remarks

The update counter enables:

  • Optimistic concurrency control in distributed scenarios
  • Performance monitoring and optimization opportunities identification
  • Business intelligence on data volatility and usage patterns
  • Audit trail verification and completeness checking

Implementations should increment this counter for each logical update operation, not for internal system operations like cache refreshes or metadata updates. The counter helps distinguish between frequently and rarely modified entities for optimization and archival purposes.

Methods

BaseEntity<T>.SoftDelete() Method

Marks this entity as logically deleted without removing it from the data store. This method preserves the entity for audit purposes while excluding it from normal operations.

public virtual void SoftDelete();

Example

// Soft delete an entity
entity.SoftDelete();

// Verify deletion status
if (entity.IsSoftDeleted)
{
// Handle soft-deleted entity
logger.LogInformation("Entity {Id} has been soft deleted", entity.id);
}

Remarks

Soft deletion provides several benefits:

  • Maintains referential integrity by keeping referenced entities
  • Preserves complete audit trails for compliance and analysis
  • Allows for data recovery in case of accidental deletion
  • Supports business rules that require historical data preservation

After calling this method:

  • The entity should be excluded from normal business queries
  • Related entities may need to handle the soft-deleted state
  • The entity remains accessible for audit and recovery purposes
  • Consider updating LastUpdatedAt and LastUpdatedBy in derived implementations

This method is marked as virtual to allow derived classes to implement additional soft deletion logic, such as cascading soft deletes or business-specific cleanup operations.

NamedEntity<T> Class

Provides an abstract base class for domain entities that require human-readable identification. This class extends BaseEntity<T> by adding name and description properties for entities that need to be presented or referenced by name in user interfaces and business operations.

public abstract class NamedEntity<T> : arolariu.Backend.Common.DDD.Contracts.BaseEntity<T>

Type parameters

T

The type of the entity's primary key. Common types include System.Guid, System.Int32, and System.String.

Inheritance System.Object 🡒 arolariu.Backend.Common.DDD.Contracts.BaseEntity<T> 🡒 NamedEntity<T>

Example

// Example implementation for a product category
public class Category : NamedEntity<Guid>
{
public override required Guid id { get; init; } = Guid.NewGuid();

// Name and Description are inherited and can be used directly
public Category(string name, string description = "")
{
Name = name;
Description = description;
}
}

// Usage example
var category = new Category("Electronics", "Consumer electronics and gadgets")
{
CreatedBy = userId,
IsImportant = true
};

// The entity provides both technical and business identification
Console.WriteLine($"Category ID: {category.id}");
Console.WriteLine($"Category Name: {category.Name}");
Console.WriteLine($"Description: {category.Description}");

Remarks

NamedEntity is designed for domain entities that require human-readable identification beyond their technical identifiers. It provides a standardized structure for entities that are commonly referenced by name in business operations, user interfaces, and reporting.

The class establishes a consistent property order for JSON serialization:

  1. id - The unique technical identifier (inherited from BaseEntity<T>)
  2. Name - The human-readable name for display and reference purposes
  3. Description - Optional detailed description for additional context
  4. Audit properties - Creation, modification, and metadata fields (inherited)

Common Use Cases: - Catalog entities (products, categories, brands) - Configuration entities (settings, templates, rules) - Reference data (countries, currencies, status codes) - User-manageable entities (projects, organizations, groups)

Design Considerations: - Name property is mutable to support business requirements for renaming - Description is optional and can be empty for simple entities - Inherits full audit trail capabilities from BaseEntity - Supports soft deletion and importance marking

Properties

NamedEntity<T>.Description Property

Gets or sets an optional detailed description of the entity. This property provides additional context and information beyond the basic name.

public string Description { get; set; }

Property Value

System.String
A string containing a detailed description of the entity. Defaults to an empty string. Can be used for documentation, help text, or extended information display.

Remarks

The Description property enhances entity understanding and usability:

  • Provides detailed explanation or context for the entity
  • Supports user guidance in interfaces through help text or tooltips
  • Enables rich content for catalogs, documentation, and reports
  • Facilitates full-text search scenarios beyond just name matching

Content Guidelines: - Should provide value beyond what the name already conveys - Can include usage instructions, specifications, or business context - Consider markdown or structured text for rich formatting needs - Keep length appropriate for intended display contexts

Optional Nature: - Can be empty for simple entities where name is self-explanatory - Length and content vary based on entity complexity and business needs - Consider character limits based on storage and display requirements - May support internationalization for multi-language deployments

NamedEntity<T>.Name Property

Gets or sets the human-readable name of the entity. This property provides a business-friendly identifier for display, searching, and reference purposes.

public string Name { get; set; }

Property Value

System.String
A string representing the entity's name. Defaults to an empty string for new entities. The name should be meaningful to business users and suitable for display in user interfaces.

Remarks

The Name property serves multiple purposes in the domain model:

  • Primary display text in user interfaces and reports
  • Search and filtering criteria for entity lookup
  • Business reference in logs, audit trails, and documentation
  • Human-readable identifier in API responses and exports

Naming Guidelines: - Should be concise but descriptive enough for clear identification - Consider internationalization requirements for multi-language support - Avoid technical jargon unless the audience consists of technical users - Ensure uniqueness where business rules require it (enforced at the business logic level)

Implementation Notes: - Ordered as the second property in JSON serialization (after id) - Mutable to support business scenarios requiring entity renaming - No built-in validation - validation should be implemented in domain services - Consider implementing change tracking if name history is important

Interfaces

IAuditable Interface

Defines the contract for entities that require comprehensive audit trail capabilities. This interface ensures consistent tracking of entity lifecycle events, user accountability, and change management across the entire domain model.

public interface IAuditable

Derived
BaseEntity<T>

Example

// Example implementation in a custom entity
public class CustomEntity : IAuditable
{
public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow;
public Guid CreatedBy { get; init; }
public DateTimeOffset LastUpdatedAt { get; private set; } = DateTimeOffset.UtcNow;
public Guid LastUpdatedBy { get; private set; }
public int NumberOfUpdates { get; private set; } = 0;
public bool IsSoftDeleted { get; private set; } = false;
public bool IsImportant { get; set; } = false;

public void UpdateAuditInfo(Guid updatedBy)
{
LastUpdatedAt = DateTimeOffset.UtcNow;
LastUpdatedBy = updatedBy;
NumberOfUpdates++;
}
}

Remarks

The IAuditable interface provides essential audit functionality for compliance, debugging, and business intelligence purposes. It establishes a standard contract for:

Temporal Auditing: - Creation and modification timestamps for change tracking - UTC-based timestamps to ensure consistency across time zones - Immutable creation timestamps to preserve original entity state

User Accountability: - User identification for all create and update operations - Supports both human users and system processes through Guid identifiers - Enables detailed audit trails for security and compliance requirements

Change Metrics: - Update counters for frequency analysis and optimization - Soft deletion flags for data preservation and recovery - Business importance markers for prioritization and special handling

This interface is typically implemented by BaseEntity<T> but can be implemented independently for value objects or other constructs that require auditing. All domain entities should implement this interface to ensure consistent audit capabilities.

Properties

IAuditable.CreatedAt Property

Gets the date and time when the entity was originally created. This timestamp is immutable and represents the initial entity creation moment.

System.DateTimeOffset CreatedAt { get; init; }

Property Value

System.DateTimeOffset
A System.DateTimeOffset representing the UTC creation timestamp. This value should be set once during entity initialization and never modified.

Remarks

The creation timestamp serves multiple purposes:

  • Audit trail compliance for regulatory requirements
  • Data lifecycle management and archival policies
  • Business analytics and reporting on entity creation patterns
  • Debugging and troubleshooting by providing creation context

This property uses init-only setter to enforce immutability after object construction. The timestamp should always be in UTC to ensure consistency across different time zones and deployment environments.

IAuditable.CreatedBy Property

Gets the unique identifier of the user or system that created this entity. This provides accountability and traceability for entity creation operations.

System.Guid CreatedBy { get; init; }

Property Value

System.Guid
A System.Guid representing the creator's unique identifier. For system-generated entities, this may be a special system identifier. For user-created entities, this should be the authenticated user's identifier.

Remarks

The creator identifier enables:

  • User accountability for audit and compliance purposes
  • Security investigations and access pattern analysis
  • Business intelligence on user productivity and system usage
  • Data ownership and permission management

This property is immutable after entity creation to maintain audit integrity. System processes should use consistent, documented identifiers to distinguish automated actions from user-initiated operations.

IAuditable.IsImportant Property

Gets or sets a value indicating whether this entity is marked as important for business operations. This flag enables prioritization, special handling, and enhanced monitoring capabilities.

bool IsImportant { get; set; }

Property Value

System.Boolean
true if the entity is marked as important; otherwise, false. The specific meaning of "important" is defined by the business domain context.

Remarks

The importance flag supports various business scenarios:

  • Prioritization in processing queues and batch operations
  • Enhanced monitoring and alerting for critical entities
  • Special backup and disaster recovery procedures
  • Performance optimization for high-priority data

The interpretation of this flag depends on the specific business domain:

  • In e-commerce: VIP customers or high-value products
  • In healthcare: Critical patient records or urgent cases
  • In finance: High-value transactions or regulatory submissions
  • In logistics: Priority shipments or time-sensitive deliveries

This property has a public setter to allow business rules to dynamically adjust entity importance based on changing conditions or business requirements.

IAuditable.IsSoftDeleted Property

Gets a value indicating whether this entity has been logically deleted. Soft deletion preserves data for audit purposes while excluding it from normal operations.

bool IsSoftDeleted { get; }

Property Value

System.Boolean
true if the entity has been logically deleted; otherwise, false. Soft-deleted entities should be excluded from normal business queries and operations.

Remarks

Soft deletion provides several advantages over physical deletion:

  • Preserves referential integrity in complex domain models
  • Maintains complete audit trails for compliance requirements
  • Enables data recovery in case of accidental deletion
  • Supports business rules requiring historical data preservation

Applications should implement query filters to automatically exclude soft-deleted entities from normal operations while preserving access for audit and recovery scenarios. The soft deletion state should be considered when implementing business logic and data access patterns.

IAuditable.LastUpdatedAt Property

Gets the date and time when the entity was last modified. This timestamp is updated automatically whenever the entity undergoes changes.

System.DateTimeOffset LastUpdatedAt { get; }

Property Value

System.DateTimeOffset
A System.DateTimeOffset representing the UTC timestamp of the most recent modification. Initially set to the creation time and updated with each subsequent change.

Remarks

The last updated timestamp supports:

  • Optimistic concurrency control to prevent conflicting updates
  • Change frequency analysis for performance optimization
  • Data freshness validation for caching and synchronization
  • Audit trail completeness verification

Implementations should update this timestamp whenever any property of the entity changes, ensuring accurate change tracking. The timestamp should always be in UTC for consistency across different environments and time zones.

IAuditable.LastUpdatedBy Property

Gets the unique identifier of the user or system that last modified this entity. This provides accountability for the most recent changes to the entity.

System.Guid LastUpdatedBy { get; }

Property Value

System.Guid
A System.Guid representing the identifier of the user or system that performed the most recent update operation. Initially set to the creator's identifier.

Remarks

The last updater identifier facilitates:

  • Change attribution for audit and accountability purposes
  • Security monitoring and access pattern analysis
  • Collaborative editing scenarios and conflict resolution
  • Performance analysis of user and system operations

This identifier should be updated whenever the entity is modified, regardless of whether the modification is performed by a user or an automated system process. Consistent identifier management enables accurate audit trails and security monitoring.

IAuditable.NumberOfUpdates Property

Gets the total number of update operations performed on this entity since creation. This counter provides insights into entity change frequency and system usage patterns.

int NumberOfUpdates { get; }

Property Value

System.Int32
An integer representing the cumulative count of update operations. Starts at 0 for newly created entities and increments with each modification.

Remarks

The update counter enables:

  • Optimistic concurrency control in distributed scenarios
  • Performance monitoring and optimization opportunities identification
  • Business intelligence on data volatility and usage patterns
  • Audit trail verification and completeness checking

Implementations should increment this counter for each logical update operation, not for internal system operations like cache refreshes or metadata updates. The counter helps distinguish between frequently and rarely modified entities for optimization and archival purposes.

// was this page useful?