Conventions


How to set conventions

  • Access the conventions via the Conventions property of the DocumentStore object.

  • The conventions set on a Document Store will apply to ALL sessions and operations associated with that store.

  • Customizing the conventions can only be set before calling DocumentStore.Initialize().
    Trying to do so after calling Initialize() will throw an exception.

using (var store = new DocumentStore()
{
    Conventions =
    {
        // Set conventions HERE, e.g.:
        MaxNumberOfRequestsPerSession = 50,
        AddIdFieldToDynamicObjects = false
        // ...
    }
}.Initialize())
{
    // * Here you can interact with the RavenDB store:
    //   open sessions, create or query for documents, perform operations, etc.
    
    // * Conventions CANNOT be set here after calling Initialize()
}

Conventions:

AddIdFieldToDynamicObjects


  • Use the AddIdFieldToDynamicObjects convention to determine whether an Id field is automatically added
    to dynamic objects when storing new entities via the session.

  • DEFAULT: true

// Syntax:
public bool AddIdFieldToDynamicObjects { get; set; }

AggressiveCache.Duration


  • Use the AggressiveCache.Duration convention to define the aggressive cache duration period.

  • DEFAULT: 1 day

// Syntax:
public TimeSpan Duration { get; set; }

AggressiveCache.Mode


  • Use the AggressiveCache.Mode convention to define the aggressive cache mode.
    (AggressiveCacheMode.TrackChanges or AggressiveCacheMode.DoNotTrackChanges)

  • DEFAULT: AggressiveCacheMode.TrackChanges

// Syntax:
public AggressiveCacheMode Mode { get; set; }

AsyncDocumentIdGenerator


  • Use the AsyncDocumentIdGenerator convention to define the document ID generator method that will be used when storing a document without explicitly specifying its Id.

  • You can override this global ID generator for specific object types using the RegisterAsyncIdConvention convention.

  • DEFAULT:
    The default document ID generator is the GenerateDocumentIdAsync method, which is part of the HiLoIdGenerator object within the DocumentStore. This method implements the HiLo algorithm to ensure efficient ID generation when storing a document without explicitly specifying its Id.

// Customize ID generation for all collections
AsyncDocumentIdGenerator = (database, obj) =>
{
    var objectType = obj.GetType().Name;  // e.g., Person, Order, etc.
    var timestamp = DateTime.UtcNow.Ticks; // Get the current timestamp

    // Format the ID as {ObjectType}/{Ticks}
    var id = $"{objectType}/{timestamp}";

    return Task.FromResult(id);
}
// Syntax:
public Func<string, object, Task<string>> AsyncDocumentIdGenerator { get; set; }

CreateHttpClient


  • Use the CreateHttpClient convention to modify the HTTP client your client application uses.

  • For example, implementing your own HTTP client can be useful when you'd like your clients to provide the server with tracing info.

  • If you override the default CreateHttpClient convention we advise that you also set the HTTP client type correctly using the HttpClientType convention.

CreateHttpClient = handler =>
{
    // Your HTTP client code here, e.g.:
    var httpClient = new MyHttpClient(new HttpClientXRayTracingHandler(new HttpClientHandler()));
    return httpClient;
}
// Syntax:
public Func<HttpClientHandler, HttpClient> CreateHttpClient { get; set; }

DisableAtomicDocumentWritesInClusterWideTransaction


  • EXPERT ONLY:
    Use the DisableAtomicDocumentWritesInClusterWideTransaction convention to disable automatic
    atomic writes with cluster write transactions.

  • When set to true, will only consider explicitly added compare exchange values to validate cluster wide transactions.

  • DEFAULT: false

// Syntax:
public bool? DisableAtomicDocumentWritesInClusterWideTransaction { get; set; }

DisableTcpCompression


  • When setting the DisableTcpCompression convention to true, TCP data will not be compressed.

  • DEFAULT: false

// Syntax:
public bool DisableTcpCompression { get; set; }

DisableTopologyCache


  • By default, the client caches the cluster's topology in *.raven-cluster-topology files on disk.
    When all servers provided in the DocumentStore.Urls property are down or unavailable, the client will load the topology from the latest file and try to connect to nodes that are not listed in the URL property.

  • This behavior can be disabled when setting the DisableTopologyCache convention to true.
    In such a case:

    • The client will not load the topology from the cache upon failing to connect to a server.
    • Even if the client is configured to receive topology updates from the server, no topology files will be saved on disk, thus preventing the accumulation of these files.
  • DEFAULT: false

// Syntax:
public bool DisableTopologyCache { get; set; }

DisableTopologyUpdates


  • When setting the DisableTopologyUpdates convention to true,
    no database topology updates will be sent from the server to the client (e.g. adding or removing a node).

  • DEFAULT: false

// Syntax:
public bool DisableTopologyUpdates { get; set; }

FindClrType


  • Use the FindClrType convention to define a function that finds the CLR type of a document.

  • DEFAULT:
    The CLR type is retrieved from the Raven-Clr-Type property under the @metadata key in the document.

// The default implementation is:
FindClrType = (_, doc) =>
{
    if (doc.TryGet(Constants.Documents.Metadata.Key, out BlittableJsonReaderObject metadata) &&
        metadata.TryGet(Constants.Documents.Metadata.RavenClrType, out string clrType))
        return clrType;

    return null;
}
// Syntax:
public Func<string, BlittableJsonReaderObject, string> FindClrType { get; set; }

FindClrTypeName


  • Use the FindClrTypeName convention to define a function that returns the CLR type name from a given type.

  • DEFAULT: The entity's full name with the assembly name is returned.

// Syntax:
public Func<Type, string> FindClrTypeName { get; set; }

FindClrTypeNameForDynamic


  • Use the FindClrTypeNameForDynamic convention to define a function that returns the CLR type name
    from a dynamic entity.

  • DEFAULT: The dynamic entity type is returned.

// The dynamic entity's type is returned by default
FindClrTypeNameForDynamic = dynamicEntity => dynamicEntity.GetType()
// Syntax:
public Func<dynamic, string> FindClrTypeNameForDynamic { get; set; }

FindCollectionName


  • Use the FindCollectionName convention to define a function that will customize the collection name
    from given type.

  • DEFAULT: The collection name will be the plural form of the type name.

// Here the collection name will be the type name separated by dashes
FindCollectionName = type => String.Join("-", type.Name.ToCharArray())
// Syntax:
public Func<Type, string> FindCollectionName { get; set; }

FindCollectionNameForDynamic


  • Use the FindCollectionNameForDynamic convention to define a function that will customize the
    collection name from a dynamic type.

  • DEFAULT: The collection name will be the entity's type.

// Here the collection name will be some property of the dynamic entity
FindCollectionNameForDynamic = dynamicEntity => dynamicEntity.SomeProperty
// Syntax:
public Func<dynamic, string> FindCollectionNameForDynamic { get; set; }

FindIdentityProperty


  • Use the FindIdentityProperty convention to define a function that finds the specified ID property
    in the entity.

  • DEFAULT: The entity's Id property serves as the ID property.

// If there exists a property with name "CustomizedId" then it will be the entity's ID property 
FindIdentityProperty = memberInfo => memberInfo.Name == "CustomizedId"
// Syntax:
public Func<MemberInfo, bool> FindIdentityProperty { get; set; }

FindIdentityPropertyNameFromCollectionName


  • Use the FindIdentityPropertyNameFromCollectionName convention to define a function that customizes the entity's ID property from the collection name.

  • DEFAULT: Will use the Id property.

// Will use property "CustomizedId" as the ID property
FindIdentityPropertyNameFromCollectionName = collectionName => "CustomizedId"
// Syntax:
public Func<string, string> FindIdentityPropertyNameFromCollectionName { get; set; }

FindProjectedPropertyNameForIndex


  • Use the FindProjectedPropertyNameForIndex convention to define a function that customizes the
    projected fields names that will be used in the RQL sent to the server when querying an index.

  • Given input: The indexed document type, the index name, the current path, and the property path
    that is used in a query.

  • DEFAULT: null

// Syntax:
public Func<Type, string, string, string, string> FindProjectedPropertyNameForIndex { get; set; }

FindPropertyNameForDynamicIndex


  • Use the FindPropertyNameForDynamicIndex convention to define a function that customizes the
    property name that will be used in the RQL sent to the server when making a dynamic query.

  • Given input: The indexed document type, the index name, the current path, and the property path
    that is used in a query predicate.

// The DEFAULT function:
FindPropertyNameForDynamicIndex = (Type indexedType, string indexedName, string path, string prop) =>
    path + prop
// Syntax:
public Func<Type, string, string, string, string> FindPropertyNameForDynamicIndex { get; set; }

FindPropertyNameForIndex


  • Use the FindPropertyNameForIndex convention to define a function that customizes the name of the
    index-field property that will be used in the RQL sent to the server when querying an index.

  • Given input: The indexed document type, the index name, the current path, and the property path
    that is used in a query predicate.

  • DEFAULT: []. & . are replaced by _

// The default function:
FindPropertyNameForIndex = (Type indexedType, string indexedName, string path, string prop) => 
    (path + prop).Replace("[].", "_").Replace(".", "_")
// Syntax:
public Func<Type, string, string, string, string> FindPropertyNameForIndex { get; set; }

FirstBroadcastAttemptTimeout


  • Use the FirstBroadcastAttemptTimeout convention to set the timeout for the first broadcast attempt.

  • In the first attempt, the request executor will send a single request to the selected node.
    Learn about the "selected node" in: Client logic for choosing a node.

  • A second attempt will be held upon failure.

  • DEFAULT: 5 seconds

FirstBroadcastAttemptTimeout = TimeSpan.FromSeconds(10)
// Syntax:
public TimeSpan FirstBroadcastAttemptTimeout { get; set; }

HttpClientType


  • Use the HttpClientType convention to set the type of HTTP client you're using.

  • RavenDB uses the HTTP type internally to manage its cache.

  • If you override the CreateHttpClient convention to use a non-default HTTP client,
    we advise that you also set HttpClientType so it returns the client type you are actually using.

// The type of HTTP client you are using
HttpClientType = typeof(MyHttpClient)
// Syntax:
public Type HttpClientType { get; set; }

HttpVersion


  • Use the HttpVersion convention to set the Http version the client will use when communicating
    with the server.

  • DEFAULT:

    • When this convention is explicitly set to null, the default HTTP version provided by your .NET framework is used.
    • Otherwise, the default HTTP version is set to System.Net.HttpVersion.Version11 (HTTP 1.1).

// Syntax:
public Version HttpVersion { get; set; }

IdentityPartsSeparator


  • Use the IdentityPartsSeparator convention to set the default ID separator for automatically-generated document IDs.

  • DEFAULT: / (forward slash)

  • The value can be any char except | (pipe).

  • Changing the separator affects these ID generation strategies:

// Syntax:
public char IdentityPartsSeparator { get; set; }

LoadBalanceBehavior

LoadBalancerPerSessionContextSelector

LoadBalancerContextSeed


  • Configure the load balance behavior by setting the following conventions:

    • LoadBalanceBehavior
    • LoadBalancerPerSessionContextSelector
    • LoadBalancerContextSeed
  • Learn more in the dedicated Load balance behavior article.

MaxHttpCacheSize


  • Use the MaxHttpCacheSize convention to set the maximum HTTP cache size.
    This setting will affect all the databases accessed by the Document Store.

  • DEFAULT:

    System Usable Memory Default Value
    64-bit Lower than or equal to 3GB
    Greater than 3GB and Lower than or equal to 6GB
    Greater than 6GB
    64MB
    128MB
    512MB
    32-bit 32MB
  • Disabling Caching:

  • Note: RavenDB also supports Aggressive Caching.
    Learn more about that in article Setup aggressive caching.

MaxHttpCacheSize = new Size(256, SizeUnit.Megabytes) // Set max cache size
MaxHttpCacheSize = new Size(0, SizeUnit.Megabytes) // Disable caching
// Syntax:
public Size MaxHttpCacheSize { get; set; }

MaxNumberOfRequestsPerSession


  • Use the MaxNumberOfRequestsPerSession convention to set the maximum number of requests per session.

  • DEFAULT: 30

// Syntax:
public int MaxNumberOfRequestsPerSession { get; set; }

Modify serialization of property name


  • Different clients use different casing conventions for entity field names. For example:

    Language Default casing Example
    C# PascalCase OrderLines
    Java camelCase orderLines
    JavaScript camelCase orderLines
  • By default, when saving an entity, the naming convention used by the client is reflected in the JSON document properties on the server-side.
    This default serialization behavior can be customized to facilitate language interoperability.

  • Example:

    Set CustomizeJsonSerializer and PropertyNameConverter to serialize an entity's properties as camelCase from a C# client:

    Serialization = new NewtonsoftJsonSerializationConventions
    {
        // .Net properties will be serialized as camelCase in the JSON document when storing an entity
        // and deserialized back to PascalCase
        CustomizeJsonSerializer = s => s.ContractResolver = new CamelCasePropertyNamesContractResolver()
    },
    
    // In addition, the following convention is required when
    // making a query that filters by a field name and when indexing. 
    PropertyNameConverter = memberInfo => FirstCharToLower(memberInfo.Name)
    private string FirstCharToLower(string str) => $"{Char.ToLower(str[0])}{str.Substring(1)}";
    // Syntax:
    public ISerializationConventions Serialization { get; set; }

OperationStatusFetchMode


  • Use the OperationStatusFetchMode convention to set the way an operation is getting its status when waiting for completion.

  • DEFAULT:
    By default, the value is set to ChangesApi which uses the WebSocket protocol underneath when a connection is established with the server.

  • On some older systems like Windows 7 the WebSocket protocol might not be available due to the OS and .NET Framework limitations. To bypass this issue, the value can be changed to Polling.

OperationStatusFetchMode = OperationStatusFetchMode.ChangesApi // ChangesApi | Polling
// Syntax:
public OperationStatusFetchMode OperationStatusFetchMode { get; set; }

PreserveDocumentPropertiesNotFoundOnModel


  • Loading a document using a different model will result in the removal of the missing model properties
    from the loaded entity, and no exception is thrown.

  • Setting the PreserveDocumentPropertiesNotFoundOnModel convention to true
    allows the client to check (via whatChanged or via WhatChangedFor methods) for the missing properties on the entity after loading the document.

  • DEFAULT: true

// Syntax:
public bool PreserveDocumentPropertiesNotFoundOnModel { get; set; }

ReadBalanceBehavior


  • Configure the read request behavior by setting the ReadBalanceBehavior convention.

  • Learn more in the dedicated Read balance behavior article.

RequestTimeout


  • Use the RequestTimeout convention to define the global request timeout value for all RequestExecutors created per database.

  • DEFAULT: null (the default HTTP client timout will be applied - 12h)

RequestTimeout = TimeSpan.FromSeconds(90)
// Syntax:
public TimeSpan? RequestTimeout { get; set; } 

ResolveTypeFromClrTypeName


  • Use the ResolveTypeFromClrTypeName convention to define a function that resolves the CLR type
    from the CLR type name.

  • DEFAULT: The type is returned.

// The type itself is returned by default
ResolveTypeFromClrTypeName = clrType => clrType.GetType()
// Syntax:
public Func<string, Type> ResolveTypeFromClrTypeName { get; set; }

SaveEnumsAsIntegers


  • When setting the SaveEnumsAsIntegers convention to true,
    C# enum types will be stored and queried as integers, rather than their string representations.

  • DEFAULT: false (save as strings)

// Syntax:
public bool SaveEnumsAsIntegers { get; set; } 

SecondBroadcastAttemptTimeout


  • Use the SecondBroadcastAttemptTimeout convention to set the timeout for the second broadcast attempt.

  • Upon failure of the first attempt the request executor will resend the command to all nodes simultaneously.

  • DEFAULT: 30 seconds

SecondBroadcastAttemptTimeout = TimeSpan.FromSeconds(20)
public TimeSpan SecondBroadcastAttemptTimeout { get; set; } 

SendApplicationIdentifier


  • Use the SendApplicationIdentifier convention to true to enable sending a unique application identifier to the RavenDB Server.

  • Setting to true allows the server to issue performance hint notifications to the client, e.g. during robust topology update requests which could indicate a Client API misuse impacting the overall performance.

  • DEFAULT: true

// Syntax:
public bool SendApplicationIdentifier { get; set; } 

ShouldIgnoreEntityChanges


ThrowIfQueryPageSizeIsNotSet


  • When setting the ThrowIfQueryPageSizeIsNotSet convention to true,
    an exception will be thrown if a query is performed without explicitly setting a page size.

  • This can be useful during development to identify potential performance bottlenecks since there is no limitation on the number of results returned from the server.

  • DEFAULT: false

// Syntax:
public bool ThrowIfQueryPageSizeIsNotSet { get; set; }

TopologyCacheLocation


  • Use the TopologyCacheLocation convention to change the location of the topology cache files
    (*.raven-database-topology & *.raven-cluster-topology).

  • Directory existence and writing permissions will be checked when setting this value.

  • DEFAULT: AppContext.BaseDirectory (The application's base directory)

TopologyCacheLocation = @"C:\RavenDB\TopologyCache"
// Syntax:
public string TopologyCacheLocation { get; set; } 

TransformTypeCollectionNameToDocumentIdPrefix


  • Use the TransformTypeCollectionNameToDocumentIdPrefix convention to define a function that will
    customize the document ID prefix from the the collection name.

  • DEFAULT:
    By default, the document id prefix is determined as follows:

Number of uppercase letters in collection name Document ID prefix
<= 1 Use the collection name with all lowercase letters
> 1 Use the collection name as is, preserving the original case

// Syntax:
public Func<string, string> TransformTypeCollectionNameToDocumentIdPrefix { get; set; }

UseCompression


  • Set the UseCompression convention to true in order to accept the response in compressed format and the automatic decompression of the HTTP response content.

  • A gzip compression is always applied when sending content in an HTTP request.

  • DEFAULT: true

// Syntax:
public bool UseCompression { get; set; }

UseOptimisticConcurrency


  • When setting the UseOptimisticConcurrency convention to true,
    Optimistic Concurrency checks will be applied for all sessions opened from the Document Store.

  • Learn more about Optimistic Concurrency and the various ways to enable it in article
    how to enable optimistic concurrency.

  • DEFAULT: false

// Syntax:
public bool UseOptimisticConcurrency { get; set; }

WaitForIndexesAfterSaveChangesTimeout


  • Use the WaitForIndexesAfterSaveChangesTimeout convention to set the default timeout for the DocumentSession.Advanced.WaitForIndexesAfterSaveChanges method.

  • DEFAULT: 15 Seconds

WaitForIndexesAfterSaveChangesTimeout = TimeSpan.FromSeconds(10)
// Syntax:
public TimeSpan WaitForIndexesAfterSaveChangesTimeout { get; set; }

WaitForNonStaleResultsTimeout


  • Use the WaitForNonStaleResultsTimeout convention to set the default timeout used by the
    WaitForNonStaleResults method when querying.

  • DEFAULT: 15 Seconds

WaitForNonStaleResultsTimeout = TimeSpan.FromSeconds(10)
// Syntax:
public TimeSpan WaitForNonStaleResultsTimeout { get; set; }

WaitForReplicationAfterSaveChangesTimeout


  • Use the WaitForReplicationAfterSaveChangesTimeout convention to set the default timeout for the
    DocumentSession.Advanced.WaitForReplicationAfterSaveChangesmethod.

  • DEFAULT: 15 Seconds

WaitForReplicationAfterSaveChangesTimeout = TimeSpan.FromSeconds(10)
// Syntax:
public TimeSpan WaitForReplicationAfterSaveChangesTimeout { get; set; }