Vidyano.SourceGenerators
3.9.0
Prefix Reserved
dotnet add package Vidyano.SourceGenerators --version 3.9.0
NuGet\Install-Package Vidyano.SourceGenerators -Version 3.9.0
<PackageReference Include="Vidyano.SourceGenerators" Version="3.9.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
<PackageVersion Include="Vidyano.SourceGenerators" Version="3.9.0" />
<PackageReference Include="Vidyano.SourceGenerators"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add Vidyano.SourceGenerators --version 3.9.0
#r "nuget: Vidyano.SourceGenerators, 3.9.0"
#:package Vidyano.SourceGenerators@3.9.0
#addin nuget:?package=Vidyano.SourceGenerators&version=3.9.0
#tool nuget:?package=Vidyano.SourceGenerators&version=3.9.0
Disclaimer
- Use of SourceGenerators depend on available content.
- Analyzers and CodeFixes are available in any project.
Some Patterns are not supported by Analyzers at the moment:
- When Clause on Switch Expression / Statements
Generators
- Actions Generator
- BusinessRules Generator
- Context Generator
- CustomAction Generator
- Index Generator
- Model Generator
- ProjectTargetContextType Generator
- Recipients Generator
- RowSecurity Generator
- SplittedValueObjects Generator
Generated Constant classes
All generated Constant classes are available under {RootNamespace}.Service.Generated namespace.
BusinessRuleNamesPersistentObjectTypesPersistentObjectAttributeNamesProgramUnitNamesProgramUnitItemsNamesQueryNamesQuerySourcesActionNamesLanguagesMessageKeysandMessagesAppRolesWebsiteNamesObsolete.PersistentObjectTypes
Dependency Injection
By using the InitializeByCtor attribute on a field, the source generator will inject this field via the generated constructor.
The Attribute can only be applied when no constructor is provided.
public partial class CompanyActions
{
[InitializeByCtor]
private readonly IMyService myService;
}
Attribute is available via reference Vidyano.Abstractions.
Async actions
Select the async actions base before writing any overrides:
[Async]
public partial class CustomerActions { }
The attribute is Vidyano.Service.Repository.AsyncAttribute in Vidyano.Abstractions.
The async family is available when Vidyano copies AsyncPersistentObjectActionsReference<,,>
into the application, next to the synchronous PersistentObjectActionsReference<,,>. Without
it the synchronous family is generated, whatever the preference says and whether or not an
async default is declared. The generator uses
DefaultAsyncPersistentObjectActions<TContext, TEntity, TQueryEntity>, which inherits that
reference and carries application-defined constructor dependencies and constraints. It is
generated whenever the reference is present. An application can declare that default as a
partial class or provide its implementation explicitly.
Without an explicit default base, the generated sync default inherits the application's
PersistentObjectActionsReference<,,> and the async default inherits
AsyncPersistentObjectActionsReference<,,>, both from the application's Service namespace.
Explicit bases take precedence. Both references can also be used directly as actions bases;
their constructors accept the target context.
Classes with an explicit base keep that base. A conflicting [Async] produces
VIDYANO0030. For classes without an explicit selection, configure the preference:
is_global = true
actions_source_generator_preferred_base = auto
Allowed values are auto, sync, and async; invalid values produce VIDYANO0031.
The default is auto, which considers only application-declared defaults:
| Declared defaults | Auto selects |
|---|---|
| Neither | Sync |
| Only DefaultPersistentObjectActions | Sync |
| Only DefaultAsyncPersistentObjectActions | Async |
| Both | Sync |
[Async] overrides the project preference. For gradual adoption, pin the preference to
sync before introducing an async default, then mark individual classes. Selection does
not inspect method bodies. Empty classes get override IntelliSense immediately, and
changing the preference updates the generated base without restarting the editor.
The resolved preference also controls runtime fallback for entities without an actions class when using the coordinated framework version. The generator emits assembly metadata so no separate runtime setting is needed.
VIDYANO0032 warns when a project uses async persistent-object actions but declares only
DefaultPersistentObjectActions. Its custom behavior, including Where and data-security
rules, is not inherited by the async family. Declare DefaultAsyncPersistentObjectActions
and port or share that behavior. Sync-only projects do not receive this warning. Declaring
both defaults removes the warning; the generator cannot verify that their logic is equivalent.
Lookup actions have their own default per family: DefaultLookupPersistentObjectActions
for sync and DefaultLookupAsyncPersistentObjectActions for async. Either one lets the
generator create the {Entity}Actions classes for lookup entities. The async lookup default
overrides GetEntityAsync; reference and key/value sorting keep the existing Value ordering.
RavenDB session mode is selected by the operation's context. The marker does not open
another session. Context discovery recognizes TargetRavenDBAsyncContext.
Index Generator
Generate an index by adding the GenerateIndex attribute to an entity, a nested objects class within an entity, or any deeper nested structure.
Index Types
The generator supports two types of indexes:
1. Entity Indexes
For entities, this will generate:
- A partial
{Entity}class with aQueryTypeattribute. - A partial
{VEntity}QueryType class. - A partial
{Entities}_OverviewIndex class. - A
V{Entities}property on theContextif it does not already exist.
Example:
[GenerateIndex]
public partial class Customer
{
public string Id { get; set; }
public string Name { get; set; }
}
2. Fan-out Indexes (Nested Collections)
For nested objects within entities, you can create fan-out indexes that flatten nested collections. These classes can optionally be marked with [ValueObject] but this is not required:
[GenerateIndex(typeof(Country), nameof(Country.Cities), nameof(City.Streets))]
[ValueObject(typeof(Country))]
public partial class Street
{
[ValueKey]
public string Id { get; set; }
public string Name { get; set; }
}
This creates an index that fans out from Country → Cities → Streets, making it easy to query all streets across all cities in all countries.
Fan-out Index Requirements:
- Must specify a root entity type (e.g.,
typeof(Country)) - Must provide a path through collections (e.g.,
nameof(Country.Cities), nameof(City.Streets)) - The final segment in the path must be the collection containing the target class
The generated context includes query methods for each level of the fan-out path:
public partial class ProjectContext
{
// Query streets by city
public IRavenQueryable<VStreet> City_Streets(CustomQueryArgs args)
...
// Query streets by country
public IRavenQueryable<VStreet> Country_Cities_Streets(CustomQueryArgs args)
...
public IRavenQueryable<VStreet> VStreets
...
}
3. Fan-out Indexes with SplittedCollection
For value objects stored in separate documents using [SplittedCollection], the Index Generator automatically detects the splitted collection and uses the root entity's Id as the ObjectId prefix in the generated index:
public class CarChanges
{
public string Id { get; set; } = null!;
[Reference(typeof(Car))]
public string Car { get; set; } = null!;
[SplittedCollection(typeof(Car))]
public List<CarChange> Changes { get; set; } = new();
}
[GenerateIndex(typeof(CarChanges), nameof(CarChanges.Changes))]
[ValueObject(typeof(CarChanges))]
public partial class CarChange
{
[ValueKey]
public string Id { get; set; } = null!;
public string Column { get; set; } = null!;
public string? OriginalValue { get; set; }
public string? NewValue { get; set; }
}
This generates an index where the ObjectId is constructed using the Car reference (from the [SplittedCollection] attribute) instead of the CarChanges.Id, ensuring proper linking back to the root entity.
The generated context query method is named based on the splitted root type: Car_Changes instead of CarChanges_Changes:
public partial class ProjectContext
{
// Query method named after splitted root (Car) + collection (Changes)
public IRavenQueryable<VCarChange> Car_Changes(CustomQueryArgs args)
...
public IRavenQueryable<VCarChange> VCarChanges =>
...
}
Important Notes:
- Index will not be generated if
QueryTypeorIndexis already added manually, except if they are partial. - If the index contains an
Idproperty, theIIdinterface will be applied - If the index contains any audit fields, the corresponding
IAudit...interface will be applied
Additional Attributes
You can add several attributes to control the index:
On the Class
IndexReferenceProperty: When used at the class level, includes properties from the root entity or parent entities in the fan-out path for nested collection indexes.When used on a class:
[GenerateIndex(typeof(Country), nameof(Country.Cities), nameof(City.Streets))] [IndexReferenceProperty(typeof(Country), "Id")] [IndexReferenceProperty(typeof(Country), "Name", Search = true)] [IndexReferenceProperty(typeof(City), nameof(City.Name))] public partial class Street { ... }Parameters:
- First parameter: Type of the reference entity (e.g.,
typeof(Country)) - Second parameter: Property path (e.g.,
nameof(Country.Name)or"Address.CityName") - Optional
Search: Creates a second{Property}_Sortproperty to allow full search (only needed when values can contain spaces) - Optional
IgnoreProperty: Include this property in the index mapping but do not sync to Vidyano
- First parameter: Type of the reference entity (e.g.,
IndexCustomVariable: Define custom variables for use in the index Map function.[IndexCustomVariable("countryDetails", """LoadDocument<CountryDetail>(country.Id + "/details")""")]IndexCustomWhere: Add custom where clauses to filter indexed documents.[IndexCustomWhere("countryDetails != null")]IndexCustomProperty: Add custom computed properties to the index.[IndexCustomProperty("HasDetails", typeof(bool), "countryDetails != null", IgnoreProperty = true)] [IndexCustomProperty("InternalCode", typeof(string), "countryDetails.Code", Nullable = false)]Parameters:
- Optional
Nullable: Specifies if the property type is nullable (for reference types). For value types, usetypeof(bool?)directly - Optional
IgnoreProperty: Include this property in the index mapping but do not sync to Vidyano
Note: For
IndexCustomVariableandIndexCustomWhere, the order is important and will be reflected in the generated index.- Optional
On Properties
Search: Creates a second{Property}_Sortproperty to allow full search on this property.Note: This is only needed when values can contain spaces.
IgnoreForIndex: This property will not be included in the index.IgnoreProperty: This attribute will be copied to the QueryType.IndexReferenceProperty: Include properties from a reference in the index.When used on a property:
[IndexReferenceProperty(nameof(Person.Name), Search = true)] [IndexReferenceProperty("Address.CityName")] [IndexReferenceProperty("InternalCode", IgnoreProperty = true)] [Reference(typeof(Person))] public string Person { get; set; }Parameters:
- First parameter: Property path (e.g.,
nameof(Person.Name)or"Address.CityName") Search: Creates a second{Property}_Sortproperty to allow full search (only needed when values can contain spaces)IgnoreProperty: Include this reference property in the index mapping but do not sync to Vidyano
Note:
- The reference type is inferred from the
[Reference]attribute - If no
Referenceattribute is found, you can specify the type as the first parameter onIndexReferenceProperty
- First parameter: Property path (e.g.,
[JsonProperty(DefaultValueHandling = Ignore | IgnoreAndPopulate)]on a non-nullableboolproperty:Json.NET omits these fields from the stored JSON when the value equals the configured default, so the index would otherwise fault when reading a missing field. The generator emits a comparison whose result matches what a
session.Load<T>()would yield for the missing field — keeping the index in lockstep with deserialization:Handling mode Other signal Generated expression Ignore= trueC# initializerx == truebecomesx != falseIgnoreanything else (incl. [DefaultValue(true)])x == trueIgnoreAndPopulate[DefaultValue(true)]x != falseIgnoreAndPopulateanything else x == trueTwo counter-intuitive cases worth knowing:
- With
Ignore,[DefaultValue(true)]is ignored — Json.NET doesn't consult it during deserialization in this mode. - With
IgnoreAndPopulate, the C# initializer (= true) is overwritten todefault(T)—Populateconsults[DefaultValue]instead.
Applies only to non-nullable
bool.bool?properties and other types are left unchanged.- With
Complete Example
[GenerateIndex(Index = typeof(Indexes.City_Overview))]
public partial class City
{
public string Id { get; set; }
[Search]
public string Name { get; set; }
[IgnoreForIndex]
public string InternalNotes { get; set; }
[IndexReferenceProperty(nameof(Country.Name), Search = true)]
[IndexReferenceProperty(nameof(Country.Code), IgnoreProperty = true)]
[Reference(typeof(Country))]
public string Country { get; set; }
public List<Street> Streets { get; set; }
}
[GenerateIndex(typeof(City), nameof(City.Streets))]
[IndexCustomVariable("cityDetails", """LoadDocument<CityDetail>(city.Id + "/details")""")]
[IndexCustomWhere("cityDetails != null")]
[IndexCustomProperty("HasCityDetails", typeof(bool), "cityDetails != null", Nullable = false)]
[IndexReferenceProperty(typeof(City), "Country.Name")]
[ValueObject(typeof(City))]
public partial class Street
{
[ValueKey]
public string Id { get; set; }
public string Name { get; set; }
[IndexReferenceProperty(nameof(House.Id), IgnoreProperty = true)]
[Reference(typeof(House))]
public string House { get; set; }
}
UTC dates from an index (VIDYANO5180)
A DateTimeOffset read from a stored index field is in UTC. EnableLocalTimeZone converts it only on a named object with a settable date property, so a single-field Select stays in UTC. VIDYANO5180 warns on such a Select, also when the index sits behind a property, method or variable, or when the Select runs in memory on index results.
// VIDYANO5180
var lastSeen = session.Query<VMessage, Messages_Overview>().Select(x => x.CreatedOn).FirstOrDefault();
// No warning
var lastSeen = session.Query<VMessage, Messages_Overview>().Select(x => x.CreatedOn).FirstOrDefault().ToApplicationTimeZone();
var lastSeen = session.Query<VMessage, Messages_Overview>().Select(x => new VMessage { CreatedOn = x.CreatedOn }).FirstOrDefault()?.CreatedOn;
No warning is given when the value passes through ToApplicationTimeZone() (Vidyano.Core.Extensions) later in the same expression, or when the index does not store the field. No warning is given inside an index (Map/Reduce), which RavenDB translates on the server. When storage cannot be determined, the warning is given.
Code fixes:
- Convert with ToApplicationTimeZone(): when the
Selectends in a single value (First(),FirstOrDefault(),FirstOrDefaultAsync(),Max(), ...), appends.ToApplicationTimeZone()after it and addsusing Vidyano.Core.Extensions;. - Project into an anonymous type: when a field is selected on the query itself, changes
Select(x => x.CreatedOn)intoSelect(x => new { x.CreatedOn }); the rest of the code is left to you.
ToApplicationTimeZone() only runs in memory: inside the query (Select(x => x.CreatedOn.ToApplicationTimeZone())) RavenDB cannot translate it, so the warning stays.
Recipients Generator
Generate recipient and courier queue registrations by implementing IRecipient<TMessage>.
Add services.Add{ProjectName}Recipients() to register all recipients and courier queues.
Courier queue support:
Messages decorated with [CourierQueue("...")] will automatically generate .AddCourierQueue("...") calls in the registration method. Queue names are deduplicated and sorted alphabetically, and placed before the .AddRecipient<>() calls.
Example:
[CourierQueue("QueueA")]
public record QueueAMessage(string Name);
public record DefaultMessage(string Name);
public class QueueAHandler : IRecipient<QueueAMessage>
{
public Task ReceiveAsync(ReceiveArgs<QueueAMessage> args, CancellationToken cancellationToken)
=> Task.CompletedTask;
}
public class DefaultHandler : IRecipient<DefaultMessage>
{
public Task ReceiveAsync(ReceiveArgs<DefaultMessage> args, CancellationToken cancellationToken)
=> Task.CompletedTask;
}
Generated output:
public static class RecipientsEx
{
public static IServiceCollection AddMyProjectRecipients(this IServiceCollection services)
{
return services
.AddCourierQueue("QueueA")
.AddRecipient<QueueAMessage, QueueAHandler>()
.AddRecipient<DefaultMessage, DefaultHandler>();
}
}
Messages without [CourierQueue] use the default queue and no AddCourierQueue call is generated for them.
RowSecurity Generator
Generate assembly metadata for every RowSecurity.Elevate(reason), narrowed RowSecurity.Elevate(reason, types) and RowSecurity.WithScope(scope, reason) call site, so Vidyano can document all Elevations and scoped runs in security.md, not only the ones reached since startup.
One attribute is generated per call site (in RowSecurityElevations.g.cs), in every namespace: the namespace settings don't apply to this generator.
Example:
// Invoices.cs
public class Invoices
{
public void Approve()
{
using var _ = RowSecurity.Elevate("Approver reads all invoices"); // Note: Line 42
}
}
Generated output:
[assembly: global::System.Reflection.AssemblyMetadataAttribute("Vidyano.RowSecurity.Elevation", "Invoices.Approve|42|Approver reads all invoices")]
The value is {FileNameWithoutExtension}.{MemberName}|{Line}|{Reason}, matching the runtime's [CallerFilePath]/[CallerMemberName]/[CallerLineNumber]. The reason comes last and may itself contain |. When the reason is not a compile-time constant, it is <non-constant> and warning VIDYANO5190 is reported.
A narrowed Elevate and a WithScope go on Vidyano.RowSecurity.NarrowedRun, with what they lift before the reason.
Example:
// StampJob.cs
namespace App;
public class StampJob
{
public void Run()
{
using var _ = RowSecurity.Elevate("Stamps every car", [typeof(Car), typeof(Bus)]); // Note: Line 50
}
}
// Webhook.cs
namespace App;
public class Webhook
{
public void Post(CompanyScope scope)
{
using var _ = RowSecurity.WithScope(scope, "Webhook for one company"); // Note: Line 60
}
}
Generated output:
[assembly: global::System.Reflection.AssemblyMetadataAttribute("Vidyano.RowSecurity.NarrowedRun", "StampJob.Run|50|types:App.Bus;App.Car|Stamps every car")]
[assembly: global::System.Reflection.AssemblyMetadataAttribute("Vidyano.RowSecurity.NarrowedRun", "Webhook.Post|60|scope:App.CompanyScope|Webhook for one company")]
The value is {FileNameWithoutExtension}.{MemberName}|{Line}|{Lifts}|{Reason}. {Lifts} is types:{T1};{T2} (full names, ordinal-sorted, deduped) or scope:{TScope}. Types that are not all typeof(...) of known types in an array or collection expression (a variable, a spread, an empty list or typeof(T)) give types:<non-constant> and warning VIDYANO5194; an open type parameter as scope gives scope:<type-parameter:T>. When the reason is not a compile-time constant, it is <non-constant> and warning VIDYANO5190 is reported.
Row-security analyzers (VIDYANO5191, VIDYANO5192, VIDYANO5193)
Three early-feedback rules for apps on a Vidyano version with row security (only reported when Vidyano.Service.RowSecurity exists). The runtime guard is the real protection, so all ship as Info; raise them via .editorconfig (e.g. dotnet_diagnostic.VIDYANO5191.severity = warning) once the app opts into row security. Each rule (and VIDYANO5190) links to its section on Analyzer warnings, with examples and how to fix it.
VIDYANO5191- a raw load (IDocumentSession.Load,IAsyncDocumentSession.LoadAsync, EF CoreDbSet<T>.Find(Async),DbContext.Find(Async)) of an id that comes from the client:CustomActionArgs.SelectedItems, theObjectIdofargs.Parent(CustomActionArgs/CustomQueryArgs),GetStreamArgs.Keyor anyApiArgsproperty. Load it through Vidyano or give its type a Row Policy.VIDYANO5192- a raw query that bypasses the row-security filter (EF CoreFromSql(Raw/Interpolated),Database.SqlQuery(Raw),Database.ExecuteSql(Raw/Interpolated)(Async); RavenDBAdvanced.RawQuery,AsyncRawQuery,Stream,StreamAsync) outside ausingonRowSecurity.Elevate(...). A narrowedElevate(reason, types)only covers a typed raw query (FromSql*,RawQuery<T>,AsyncRawQuery<T>,Stream<T>,StreamAsync<T>) whoseTis one of its types or derives from or implements one;ExecuteSql*andSqlQuery*need the fullElevate(reason).RowSecurity.WithScopeis not an elevation.VIDYANO5193- an override ofGetEntity/GetEntityAsynconPersistentObjectActionswhose entity type has nob.Anchor<TRow, TSource>(...)/b.AnchorAny<TRow>(...)declaration in the compilation (only whenVidyano.Service.RowSecurityBuilderexists). Such an override may build the row from the ObjectId, so no query filter saw it; the Anchors are what row security checks on that load.
session.Load<Order>(args.SelectedItems[0].Id); // VIDYANO5191
session.Advanced.RawQuery<Order>("from Orders"); // VIDYANO5192
using (RowSecurity.Elevate("Nightly export reads all orders"))
session.Advanced.RawQuery<Order>("from Orders"); // OK
VIDYANO5191 and VIDYANO5192 are lexical and shallow: the id expression or one local it is read from (also a deconstruction such as var (id, _) = args.Key.SplitObjectId()), and a using in the same method, local function or lambda body (a raw query in a lambda inside the using is still reported).
SplittedValueObjects Generator
Generate registration for splitted value objects by adding the SplittedCollection attribute to a collection property.
Add services.AddSplittedValueObjects() to register all splitted value objects.
Attribute syntax:
[SplittedCollection(typeof(RootType), suffix?: string)]
Parameters:
- First parameter (required):
typeof(RootType)- The root entity type - Second parameter (optional):
suffix- Id suffix (e.g.,"/invoiceLines")
Requirements:
- Element type must be decorated with
[ValueObject] - Containing class must have a
[Reference]property of the RootType
Example:
public class CarChanges
{
public string Id { get; set; } = null!;
[Reference(typeof(Car))]
public string Car { get; set; } = null!;
[SplittedCollection(typeof(Car))]
public List<CarChange> Changes { get; set; } = new();
}
Analyzers
Virtual calculated properties (VIDYANO5200, VIDYANO5201, VIDYANO5202, VIDYANO5203, VIDYANO5204, VIDYANO5205)
A property with [Calculated] or an attribute derived from it ([Virtual], [EndDateComputed], a module's own attribute) that is declared virtual is also calculated on the form (CronosCore #932): its formula runs on a subclass whose virtual properties read and write the attributes of the form. That only works when the actions run it and the formula has all its inputs:
VIDYANO5200: the formula (CalculatedMethods.Add/AddAsync,CalculatedProperties.Add/AddAsync) reads a property of the entity that is not inDependentOn; a property of the entity without a public setter, as a get-only computed one, is not counted.VIDYANO5201: a property inDependentOncannot be overridden or does not exist, it needs a public virtual getter and setter.VIDYANO5202: a property inDependentOnhas no"TriggersRefresh": truein the model json (App_Data/Model/<Schema>/<Entity>.json), so changing it on the form does not refresh the form. It is reported in the model json, in the project with theApp_Datajson files.VIDYANO5203: a property inDependentOnis not an attribute of the PersistentObject, so the form reads a default instead of the stored value. It is reported on the calculated property in the model json.VIDYANO5204: the formula does not reach the Entity manager of CronosCore, the only one the form runs: it is not registered (a[Calculated]one isVIDYANO5090), it is only registered withCalculatedProperties.Add/AddAsync, or the attribute has a[CalculatedMethodsManager]other than Entity, Virtual or EndDateComputed (a module manager, as[DataSecurityMember]). It is not reported when anothervirtualcalculated property has it inDependentOn, as the form then only reads its value.VIDYANO5205: avirtualcalculated property is an attribute of the PersistentObject, but{Type}Actionsand its base classes in source (without{Type}Actions:DefaultPersistentObjectActionsorDefaultAsyncPersistentObjectActions) never callthis.OnRefreshCalculatedMethods(args)inOnRefreshorawait this.OnRefreshCalculatedMethodsAsync(args, cancellationToken)inOnRefreshAsync, so the form never calculates it. It is reported on the calculated property in the model json.
They only run in projects that reference CronosCore.RavenDB 4.5.0 or later.
static ChargePoint()
{
CalculatedMethods.Add<ChargePoint>(nameof(Position), (cp, session) => cp.Position = $"{cp.Location}{cp.Latitude}");
}
public string? Location { get; set; }
public virtual double? Latitude { get; set; }
// VIDYANO5200: Position reads Location, which is not in DependentOn
[Virtual(nameof(Latitude))]
public virtual string? Position { get; set; }
No warning is given for a calculated property that is not declared virtual. VIDYANO5202, VIDYANO5203 and VIDYANO5205 only check a calculated property that is an attribute of the PersistentObject (VIDYANO5202 only its DependentOn properties that are attributes too), and find the entity by the Type of the PersistentObject in the root namespace of the project, the namespaces under it and the namespaces it is in, also in a referenced project.
VIDYANO5202, VIDYANO5203 and VIDYANO5205 skip a calculated property whose formula does not run on the form (VIDYANO5204), as the form does not check its dependencies and OnRefreshCalculatedMethods does not run it. For an entity in a referenced project they only skip one with a module manager, as its registrations are not in source.
A dependency can be a dotted attribute of the form, as "Range.From" for the property From of the object in Range: a read of cp.Range.From is in DependentOn with "Range.From", or with "Range" when Range itself is an attribute of the form (VIDYANO5203 reports "Range" otherwise), a read of the whole object, as $"{cp.Range}" or a get-only cp.Range.Display, needs "Range" or, once DependentOn has one of its dotted attributes, those of all its properties with a setter ("Range.From" and "Range.To"), only Range has to be virtual, and VIDYANO5202 and VIDYANO5203 check the attribute "Range.From".
Code fixes:
- Add missing DependentOn and virtual (
VIDYANO5200,VIDYANO5201): adds the missingnameof(...)(a dotted dependency as"Range.From") to the attribute andvirtualto every property inDependentOn, also the ones it just added. It only addsvirtualto a public instance property in source, and adds noDependentOnto an attribute whose constructor takes none, asDataSecurityMemberAttribute() : CalculatedAttribute([]). - Register with CalculatedMethods (
VIDYANO5204): replacesCalculatedPropertieswithCalculatedMethodsand adds theusing; a lambda without the session gets_as second parameter, and anAddAsynclambda(entity, session, cancellationToken)becomes(args, cancellationToken)withargs.Entityandargs.Sessionin its body. It is only offered for a lambda with untyped parameters (Addalso takes two typed ones) and a type argument on the method, asCalculatedProperties.Add<ChargePoint>(...), and not for anAddAsynclambda that already uses the nameargs. - Make non-virtual (
VIDYANO5204): removesvirtualfrom the property, so its formula only runs on save. It is only offered when the property is declaredvirtualin source. - Set TriggersRefresh on ... (
VIDYANO5202, Roslyn 4.9): adds"TriggersRefresh": trueto that attribute in the model json, afterName,DescriptionandIsReadOnly, and keeps the rest of the file as it is.
RavenDB Analyzers
The RAVEN### rules catch RavenDB mistakes at build time that otherwise only surface at index deploy or query execution: index definitions RavenDB's index compiler rejects, LINQ the query provider can't translate, and session/store usage that costs extra round-trips or misbehaves. They only run in projects that reference RavenDB.Client.
No rule is an error by default. Warnings are kept for code that fails at deploy time or at runtime; performance and style lints (N+1 loads, SaveChanges in a loop, a foreach over a query, a missing Include, …) ship as Info, so they show in the IDE but not in the dotnet build output. A project with TreatWarningsAsErrors still fails to build on a new RAVEN warning after the upgrade. Rules that flag code RavenDB rejects at deploy (RAVEN001–003, 005, 009–012) are worth raising to an error, and opt-in rules can be enabled, via .editorconfig:
[*.cs]
# Raise a rule to an error
dotnet_diagnostic.RAVEN001.severity = error
# Enable an opt-in rule
dotnet_diagnostic.RAVEN109.severity = suggestion
# Disable a rule
dotnet_diagnostic.RAVEN124.severity = none
To keep the warnings visible in a TreatWarningsAsErrors project without failing the build, exclude the RAVEN ids in the .csproj:
<PropertyGroup>
<WarningsNotAsErrors>$(WarningsNotAsErrors);RAVEN001;RAVEN125</WarningsNotAsErrors>
</PropertyGroup>
Many rules come with a code fix; a fix is only offered when it keeps the query or index result the same.
| Rule | Category | Default | Description |
|---|---|---|---|
| RAVEN001 | Indexes | Warning | Non-deterministic call (DateTime.Now etc.) in a projection |
| RAVEN002 | Indexes | Warning | Reduce output shape does not match a map output shape |
| RAVEN003 | Indexes | Warning | OrderBy feeding the outermost call of a projection (rejected at deploy) |
| RAVEN004 | Indexes | Warning | Configured field not produced by the projection |
| RAVEN005 | Indexes | Warning | Reduce function with no group-by |
| RAVEN006 | Indexes | Info | BCL Parse in a projection (indexing error on bad/missing data) |
| RAVEN008 | Indexes | Warning | Non-deterministic value generation in a projection |
| RAVEN009 | Indexes | Warning | Count()/Average() on the group in a reduce |
| RAVEN010 | Indexes | Warning | CreateVector/LoadVector in a map-reduce index |
| RAVEN011 | Indexes | Warning | WhereEntityIs argument is a runtime value, not a constant |
| RAVEN012 | Indexes | Warning | Spatial/vector field not assigned directly to a projection field |
| RAVEN101 | Queries | Warning | Constant Where predicate |
| RAVEN102 | Queries | Warning | All() on a Raven query |
| RAVEN103 | Queries | Warning | Distinct(IEqualityComparer) on a Raven query |
| RAVEN104 | Queries | Warning | Query references an unknown index name |
| RAVEN105 | Queries | Warning | string.Compare shape the query provider can't translate |
| RAVEN106 | Queries | Warning | LET clause before a WHERE clause |
| RAVEN107 | Queries | Warning | Where comparison between two document fields |
| RAVEN108 | Queries | Warning | ProjectInto called more than once |
| RAVEN109 | Queries | Info (opt-in) | Dynamic query that creates/uses an auto-index |
| RAVEN110 | Queries | Warning | Select on top of a scalar, named-type or second Select |
| RAVEN111 | Queries | Warning | Where comparison between two constants |
| RAVEN112 | Queries | Info | Session Load/query inside a loop (N+1) |
| RAVEN113 | Queries | Info | SaveChanges inside a loop |
| RAVEN114 | Queries | Warning | Nested field read from a composite GroupBy key (g.Key.Address.City) |
| RAVEN115 | Queries | Warning | RavenQuery.Include result not assigned to the discard |
| RAVEN116 | Queries | Warning | User-defined method inside a query lambda (untranslatable) |
| RAVEN117 | Queries | Info | Load of a reference field (could be one Include) |
| RAVEN118 | Queries | Info | OpenSession/OpenAsyncSession inside a loop |
| RAVEN119 | Queries | Info | Multiple independent Loads (batch with lazy loading) |
| RAVEN120 | Queries | Info (opt-in) | RavenDB query materialized without Take — unbounded result set |
| RAVEN121 | Queries | Info (opt-in) | Where on a materialized RavenDB query — filter runs client-side |
| RAVEN122 | Queries | Info | Per-document session.Delete in a loop (use DeleteByQueryOperation) |
| RAVEN123 | Queries | Info | Per-document session.Advanced.Patch in a loop (use PatchByQueryOperation) |
| RAVEN124 | Queries | Info | foreach over a RavenDB query loads the whole result set (use Take paging or Stream) |
| RAVEN125 | Queries | Warning | Query<TResult, TIndex> on a map index with an index-only field but no projection (source document loaded, field defaulted) |
| RAVEN126 | Queries | Info | Per-document TimeSeriesFor/CountersFor/Attachments.Get in a loop |
| RAVEN127 | Queries | Warning | Store on an in-method session that never calls SaveChanges (document not persisted) |
| RAVEN128 | Queries | Info | Existence check on a stale index gates a Store of the same type (duplicate under concurrency) |
| RAVEN132 | Queries | Info | WaitForNonStaleResults on a query (usually a design smell, not a fix) |
| RAVEN201 | Client | Warning | DocumentStore used without Initialize() |
| RAVEN202 | Client | Warning | UseOptimisticConcurrency on a cluster-wide-transaction session (SaveChanges throws) |
| RAVEN203 | Client | Warning | Session captured into a parallel delegate (not thread-safe) |
| RAVEN204 | Client | Warning | Store convention/property assigned after Initialize() (store is frozen, throws at runtime) |
| RAVEN301 | Subscriptions | Warning | store.OpenSession() inside a subscription batch handler (use batch.OpenSession()) |
Retired: RAVEN007 (named-type projections are valid), RAVEN013 (an explicit null check indexes a null value, so it is not redundant).
Projects
Main project
Additional Files & Global Usings
Add following ItemGroup to the .csproj project file.
<ItemGroup>
<AdditionalFiles Include="App_Data\**\*.json" />
<Using Include="$(MSBuildProjectName).Service.Generated" />
<Using Alias="Types" Include="$(MSBuildProjectName).Service.Generated.PersistentObjectTypes.$(MSBuildProjectName)" />
<Using Alias="AttributeNames" Include="$(MSBuildProjectName).Service.Generated.PersistentObjectAttributeNames.$(MSBuildProjectName)" />
<Using Alias="QueryNames" Include="$(MSBuildProjectName).Service.Generated.QueryNames.$(MSBuildProjectName)" />
<Using Alias="QuerySources" Include="$(MSBuildProjectName).Service.Generated.QuerySources.$(MSBuildProjectName)" />
</ItemGroup>
External Context
If the context file does not exist in the main project, you can use the appsettings.json file as an alternative, as the context will be read from there.
<ItemGroup>
<AdditionalFiles Include="appsettings.json" />
</ItemGroup>
Library project
Missing App_Data json files warning
When incorporating SourceGenerators into a library project, you may encounter a VIDYANO0010 warning indicating missing App_Data JSON files. This warning is not applicable to library projects, as they do not utilize App_Data.
To bypass this warning, two methods are available.
- By disabling the Model SourceGenerator via
.editorconfigfile (see EditorConfig Settings)
is_global = true
disable_model_source_generator = true
- By ignoring the warning via csproj file
<NoWarn>VIDYANO0010</NoWarn>
EditorConfig Settings
When your project or library does not follow the default naming conventions, you can configure the source generators via .editorconfig file.
Create or update your .editorconfig file with the following settings:
is_global = true
# Global Settings (apply to all generators)
source_generator_namespaces = MyNamespace, AnotherNamespace
source_generator_excluded_namespaces = MyNamespace.Internal
# Per-Generator Settings
# Disable specific generators
disable_model_source_generator = true
disable_actions_source_generator = true
disable_businessrules_source_generator = true
disable_context_source_generator = true
disable_customaction_source_generator = true
disable_index_source_generator = true
disable_projecttargetcontexttype_source_generator = true
disable_recipients_source_generator = true
disable_rowsecurity_source_generator = true
disable_splittedvalueobjects_source_generator = true
# Per-generator namespace configuration (overrides global settings)
model_source_generator_namespaces = MyNamespace
model_source_generator_excluded_namespaces = MyNamespace.Internal
Available Settings
| Setting | Description |
|---|---|
source_generator_namespaces |
Comma-separated list of namespaces to include (global) |
source_generator_excluded_namespaces |
Comma-separated list of namespaces to exclude (global) |
disable_{generator}_source_generator |
Set to true to disable a specific generator |
{generator}_source_generator_namespaces |
Namespaces to include for a specific generator |
{generator}_source_generator_excluded_namespaces |
Namespaces to exclude for a specific generator |
Notes:
- Excluded namespaces are typically used to omit sub-namespaces from an included parent namespace (e.g., including
MyNamespacebut excludingMyNamespace.Internal). - When overriding default excluded namespaces, be aware that source generator behavior can change. For example, all generators except
customactionshould exclude the custom actions namespace (e.g.,{RootNamespace}.Service.CustomActions) to function as expected.
Generator Names
Use these names in the settings (lowercase):
model- Model Generatoractions- Actions Generatorbusinessrules- BusinessRules Generatorcontext- Context Generatorcustomaction- CustomAction Generatorindex- Index Generatorprojecttargetcontexttype- ProjectTargetContextType Generatorrecipients- Recipients Generatorrowsecurity- RowSecurity Generatorsplittedvalueobjects- SplittedValueObjects Generator
Default Behavior
By default, generators scan:
- The root namespace of your project
- The
CronosCorenamespace
And exclude:
Microsoft.*,System.*,JetBrains.*,Raven.*namespaces (always excluded){RootNamespace}.Service.CustomActionsnamespace (not forcustomaction)
Exceptions
When using EmitCompilerGeneratedFiles in .csproj project file you can get exceptions when compiling in Windows because of use of long filenames.
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
To fix this issue you need to add the following registration key (Reboot needed to take effect)
reg ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem /v LongPathsEnabled /t REG_DWORD /d 1
Code Refactorings
Extract Index, QueryType and Context members
When you need to customize a generated index beyond what the [GenerateIndex] attribute supports, you can "eject" the generated code into explicit files using the Extract Index, QueryType and Context members code refactoring.
How to Use
- Place your cursor on the
[GenerateIndex]attribute - Open the lightbulb menu (Ctrl+. or Cmd+.)
- Select Vidyano → Extract Index, QueryType and Context members
What It Does
The refactoring extracts the generated code into explicit files:
- Index class - Creates
{IndexClassName}.cs(e.g.,Customers_Overview.cs) - QueryType class - Creates
V{ClassName}.cs(e.g.,VCustomer.cs) - Context property - Adds the query property to your existing context class
The refactoring also:
- Replaces
[GenerateIndex]with[QueryType(typeof(V{ClassName}))] - Removes index-related attributes from the model class:
- Class-level:
[IndexCustomProperty],[IndexCustomVariable],[IndexCustomWhere] - Both class-level and property-level:
[IndexReferenceProperty] - Property-level:
[IndexReference](obsolete),[Search],[IgnoreForIndex]
- Class-level:
- Adds required using directives
- Places files in folders matching the generated namespace structure
Example
Before:
[GenerateIndex]
[IndexCustomProperty("FullName", typeof(string), "Name + \" \" + Surname")]
public partial class Customer
{
public string Id { get; set; }
[Search]
public string Name { get; set; }
public string Surname { get; set; }
}
After applying the refactoring:
// Customer.cs - Original file modified
[QueryType(typeof(VCustomer))]
public partial class Customer
{
public string Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
// Indexes/Customers_Overview.cs - New file created
public partial class Customers_Overview : AbstractIndexCreationTask<Customer, VCustomer>
{
public Customers_Overview()
{
Map = customers => from customer in customers
select new VCustomer
{
Id = customer.Id,
Name = customer.Name,
Name_Sort = customer.Name,
Surname = customer.Surname,
FullName = customer.Name + " " + customer.Surname
};
// ... index configuration
}
}
// VCustomer.cs - New file created
public partial class VCustomer : IId
{
public string Id { get; set; }
public string Name { get; set; }
public string Name_Sort { get; set; }
public string Surname { get; set; }
public string FullName { get; set; }
}
When to Use
Use this refactoring when you need to:
- Add custom index configuration not supported by attributes
- Modify the Map/Reduce logic
- Add custom index settings or analyzers
- Have full control over the generated code
Note: After extracting, the Index generator will no longer generate code for this entity. You are now responsible for maintaining the index, query type, and context property manually.
Backwards Compatibility
For backwards compatibility we created an Obsolete PersitentObjectTypes class (old version).
The only thing you need todo when upgrading to the new source generator is changing the using in de .csproj project file by adding the Generated.Obsolete namespace.
<Using Alias="Types" Include="Fleet.Service.Generated.Obsolete.PersistentObjectTypes.Fleet" />
This way the project wil run as before.
Note: If you add the new usings directly you can use de CodeFix to update to the correct code.
Learn more about Target Frameworks and .NET Standard.
This package has no dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.9.0 | 285 | 12/2/2026 |
| 3.8.0 | 268 | 11/30/2026 |
| 3.7.0 | 3,499 | 11/6/2026 |
| 3.6.1 | 7,296 | 10/1/2026 |
| 3.6.0 | 2,660 | 9/22/2026 |
| 3.5.0 | 31,326 | 2/25/2026 |
| 3.4.0 | 21,101 | 12/10/2025 |
| 3.3.0 | 831 | 12/3/2025 |
| 3.2.0 | 628 | 11/24/2025 |
| 3.1.0 | 752 | 11/18/2025 |
| 3.0.0 | 482 | 11/7/2025 |
| 2.23.0 | 2,108 | 9/19/2025 |
| 2.22.1 | 2,375 | 5/16/2025 |
| 2.22.0 | 482 | 5/13/2025 |
| 2.21.2 | 1,980 | 3/12/2025 |
| 2.21.1 | 318 | 3/12/2025 |
| 2.21.0 | 617 | 3/5/2025 |
| 2.19.1 | 1,535 | 1/23/2025 |
| 2.19.0 | 640 | 1/16/2025 |