Table of Contents

Class BaseEntity<T>

Namespace
arolariu.Backend.Common.DDD.Contracts
Assembly
arolariu.Backend.Common.dll

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> : IAuditable

Type Parameters

T

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

Inheritance
BaseEntity<T>
Implements
Derived
Inherited Members

Examples

// 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

CreatedAt

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

[JsonPropertyOrder(245)]
public DateTimeOffset CreatedAt { get; init; }

Property Value

DateTimeOffset

A 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.

CreatedBy

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

[JsonPropertyOrder(246)]
public Guid CreatedBy { get; init; }

Property Value

Guid

A 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.

IsImportant

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.

[JsonPropertyOrder(250)]
public bool IsImportant { get; set; }

Property Value

bool

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.

IsSoftDeleted

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

[JsonPropertyOrder(251)]
public bool IsSoftDeleted { get; protected set; }

Property Value

bool

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.

LastUpdatedAt

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

[JsonPropertyOrder(247)]
public DateTimeOffset LastUpdatedAt { get; protected set; }

Property Value

DateTimeOffset

A 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.

LastUpdatedBy

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.

[JsonPropertyOrder(248)]
public Guid LastUpdatedBy { get; protected set; }

Property Value

Guid

A 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.

NumberOfUpdates

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.

[JsonPropertyOrder(249)]
public int NumberOfUpdates { get; set; }

Property Value

int

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.

id

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.

[JsonPropertyOrder(0)]
[SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Cosmos DB requires lowercase 'id' property name for document identification.")]
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: - Guid: Recommended for distributed systems and global uniqueness - int: Suitable for sequential, auto-incrementing scenarios - string: Used for natural keys or external system identifiers

Methods

SoftDelete()

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()

Examples

// 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.