From cdd4a7bc7c8cf92af2d30817c39d05e173e543b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?SAL=C4=B0H=20=C3=96ZKARA?= Date: Tue, 7 Jul 2026 08:48:13 +0300 Subject: [PATCH] docs: clarify low-code image resize behavior --- docs/en/low-code/fluent-api.md | 838 ++++++++++++++++++--------------- docs/en/low-code/model-json.md | 9 + 2 files changed, 463 insertions(+), 384 deletions(-) diff --git a/docs/en/low-code/fluent-api.md b/docs/en/low-code/fluent-api.md index 92cbf70b79..c9c4ea9e33 100644 --- a/docs/en/low-code/fluent-api.md +++ b/docs/en/low-code/fluent-api.md @@ -1,576 +1,646 @@ ```json //[doc-seo] { - "Description": "Define dynamic entities using .NET attributes and configure them with the Fluent API in the ABP Low-Code System for advanced source-controlled model configuration." + "Description": "Define ABP Low-Code entities in C# with attributes and refine them with the Fluent API. This page documents the developer-facing code-first surface, including entity/property attributes, validation behavior, attachments, file/image options, enums, and fluent configuration helpers." } ``` # Attributes & Fluent API -> **Preview:** Attributes and Fluent API configuration for the Low-Code System are preview APIs. Prefer the designer for normal modeling work, and review release notes before relying on these APIs in long-lived integrations. +> **Preview:** Attributes and Fluent API configuration for the Low-Code System are preview APIs. Prefer the designer for day-to-day modeling work, and review release notes before relying on these APIs in long-lived integrations. -Use the [Low-Code Designer](designer.md) for day-to-day entity, page, form, and filter work. C# attributes and the Fluent API are advanced configuration options for teams that need source-controlled model definitions, compile-time checking, or programmatic overrides. +Use the [Low-Code Designer](designer.md) for runtime pages, forms, filters, dashboards, menus, and page groups. The code-first surface documented here is for source-controlled model metadata: entity definitions, property metadata, enums, validation, attachments, relationships, and runtime overrides. + +## What This Surface Configures + +Attributes and Fluent API can define or override: + +* entity registration and display names +* parent-child entity structure +* default display properties for lookups +* property types, defaults, uniqueness, required state, and storage shape +* foreign keys to dynamic or reference entities +* file and image upload constraints +* entity attachments +* enum registration +* command interceptors +* cross-field validations + +They do **not** define page titles, field placements, tabs, form layouts, filters, dashboards, menus, or page groups. Configure those in the designer or in [Model Descriptor Files](model-json.md). ## Quick Start -### Step 1: Define an Entity +### Step 1: Define a Dynamic Enum and Entity ````csharp -[DynamicEntity] -[DynamicEntityUI(PageTitle = "Products")] +[DynamicEnum] +public enum ProductStatus +{ + Draft = 0, + Active = 1, + Discontinued = 2 +} + +[DynamicEntity(DefaultDisplayPropertyName = nameof(Name))] +[DynamicEntityUI("Products")] +[DynamicEntityAttachments( + "application/pdf", + "image/png", + "image/jpeg", + MaxFileCount = 5, + MaxFileSizeBytes = 5 * 1024 * 1024 +)] public class Product : DynamicEntityBase { + [Required] + [StringLength(128)] [DynamicPropertyUnique] - public string Name { get; set; } + public string Name { get; set; } = null!; - [DynamicPropertyUI(DisplayName = "Unit Price")] + [Display(Name = "Unit Price")] + [DynamicPropertyType(EntityPropertyType.Money)] + [DynamicPropertyDefaultValue("0")] public decimal Price { get; set; } - public int StockCount { get; set; } - - public DateTime? ReleaseDate { get; set; } + public ProductStatus Status { get; set; } + + [DynamicForeignKey("Catalog.Categories.Category", "Name", ForeignAccess.View)] + public Guid? CategoryId { get; set; } + + [DynamicPropertyFileOptions( + "application/pdf", + MaxSizeBytes = 5 * 1024 * 1024 + )] + public string? SpecSheet { get; set; } + + [DynamicPropertyImageOptions( + "image/png", + "image/jpeg", + MaxWidth = 1024, + MaxHeight = 1024, + MaxSizeBytes = 2 * 1024 * 1024, + ResizeMode = "fit" + )] + public string? HeroImage { get; set; } + + [DynamicPropertyNotMapped] + public string? SearchSummary { get; set; } } ```` -### Step 2: Add Migration and Run +### Step 2: Register the Assembly and Initialize the Model -```bash -dotnet ef migrations add Added_Product -dotnet ef database update -``` +````csharp +AbpDynamicEntityConfig.SourceAssemblies.Add( + new DynamicEntityAssemblyInfo(typeof(MyDomainModule).Assembly) +); -After migrations and runtime startup, the React low-code runtime can render a Product management page with data grid, create/edit forms, search, sorting, filters, and pagination. +await DynamicModelManager.Instance.InitializeAsync(); +```` -### Step 3: Add Relationships +### Step 3: Apply Fluent Overrides When Needed ````csharp -[DynamicEntity] -[DynamicEntityUI(PageTitle = "Orders")] -public class Order : DynamicEntityBase -{ - [DynamicForeignKey("MyApp.Customers.Customer", "Name", ForeignAccess.Edit)] - public Guid CustomerId { get; set; } - - public decimal TotalAmount { get; set; } - public bool IsDelivered { get; set; } -} - -[DynamicEntity(Parent = "MyApp.Orders.Order")] -public class OrderLine : DynamicEntityBase +AbpDynamicEntityConfig.EntityConfigurations.Configure(entity => { - [DynamicForeignKey("MyApp.Products.Product", "Name")] - public Guid ProductId { get; set; } - - public int Quantity { get; set; } - public decimal Amount { get; set; } -} + entity.WithDisplayName("Catalog Products"); + entity.EnableAttachments( + 10, + 5 * 1024 * 1024, + 20 * 1024 * 1024, + "application/pdf", + "image/png", + "image/jpeg" + ); + + entity.AddOrGetProperty("DiscountedPrice") + .AsMoney() + .WithDefaultValue("0"); + + entity.AddCrossFieldValidation( + "DiscountedPrice", + "Price", + EntityCrossFieldValidationOperators.LessThanOrEqual, + "Discounted price cannot exceed unit price." + ); + + entity.GetProperty("HeroImage").AsImage( + 2 * 1024 * 1024, + 1024, + 1024, + "fit", + "image/png", + "image/jpeg" + ); +}); ```` -The `Order` page now has a foreign key dropdown for Customer, and `OrderLine` is managed as a nested child inside the Order detail modal. - ## Three-Layer Configuration System -The Low-Code System uses a layered configuration model. From lowest to highest priority: +From lowest to highest priority: -1. **Code Layer** — C# classes with `[DynamicEntity]` and other attributes -2. **JSON Descriptor Layer** — source-controlled descriptor files under `_Dynamic` (see [Model Descriptor Files](model-json.md)) -3. **Fluent Layer** — `AbpDynamicEntityConfig.EntityConfigurations` +1. **Code layer**: C# classes with `[DynamicEntity]`, property attributes, and CLR validation attributes +2. **JSON descriptor layer**: source-controlled descriptor files under `_Dynamic` +3. **Fluent layer**: `AbpDynamicEntityConfig.EntityConfigurations` -A `DefaultLayer` runs last to fill in any missing values with conventions. +A `DefaultLayer` runs last to fill in conventions such as required validation for non-nullable properties. -> When the same entity or property is configured in multiple layers, the higher-priority layer wins. +> When the same value is set in multiple layers, the higher-priority layer wins. ## C# Attributes Reference -### `[DynamicEntity]` +### Entity-Level Attributes + +| Attribute | Use it for | Key members | +|-----------|------------|-------------| +| `[DynamicEntity]` | Marks a CLR class as a low-code entity | `Parent`, `DefaultDisplayPropertyName` | +| `[DynamicEntityUI]` | Sets the entity display name used by the model | `DisplayName` | +| `[DynamicEntityAttachments]` | Enables and limits entity attachments | `IsEnabled`, `MaxFileCount`, `MaxFileSizeBytes`, `MaxTotalSizeBytes`, `AllowedContentTypes` | +| `[DynamicEntityCommandInterceptor]` | Adds `Create` / `Update` / `Delete` JavaScript interceptors | `Name`, `Type`, `Javascript` | +| `[DynamicEnum]` | Registers a CLR enum for low-code enum usage | No properties | + +#### `[DynamicEntity]` -Marks a class as a dynamic entity. The entity name is derived from the class namespace and name. +Use `[DynamicEntity]` on any class that should participate in the low-code model. ````csharp -[DynamicEntity] +[DynamicEntity(DefaultDisplayPropertyName = nameof(Name))] public class Product : DynamicEntityBase { - public string Name { get; set; } - public decimal Price { get; set; } + public string Name { get; set; } = null!; } ```` -Use the `Parent` property for parent-child (master-detail) relationships: +`DefaultDisplayPropertyName` defaults to `"Id"`. Set it when lookups and relation labels should show another field such as `Name` or `Code`. + +For parent-child structures, set `Parent` by full entity name. The attribute also has a `Type` constructor overload when the parent CLR type is available: ````csharp -[DynamicEntity(Parent = "MyApp.Orders.Order")] +[DynamicEntity("Catalog.Orders.Order")] public class OrderLine : DynamicEntityBase { + [DynamicForeignKey("Catalog.Products.Product", "Name")] public Guid ProductId { get; set; } - public int Quantity { get; set; } } ```` -### `[DynamicEntityUI]` +When `Parent` is set and the child class does not already declare `Id`, the code layer adds that mapped `Guid` foreign-key property automatically. -Configures entity-level UI. Entities with `PageTitle` get a menu item and a dedicated page: +#### `[DynamicEntityUI]` + +`DynamicEntityUIAttribute` only sets the entity `DisplayName`: ````csharp [DynamicEntity] -[DynamicEntityUI(PageTitle = "Product Management")] +[DynamicEntityUI("Products")] public class Product : DynamicEntityBase { - // ... } ```` -### `[DynamicForeignKey]` +It does **not** configure page titles, form layouts, menu placement, dashboards, or other screen metadata. -Defines a foreign key relationship on a `Guid` property: +#### `[DynamicEntityAttachments]` -````csharp -[DynamicForeignKey("MyApp.Customers.Customer", "Name", ForeignAccess.Edit)] -public Guid CustomerId { get; set; } -```` - -| Parameter | Description | -|-----------|-------------| -| `entityName` | Full name of the target entity — can be a **dynamic entity** (e.g., `"MyApp.Customers.Customer"`) or a **[reference entity](reference-entities.md)** (e.g., `"Volo.Abp.Identity.IdentityUser"`) | -| `displayPropertyName` | Property to show in lookups | -| `access` | `ForeignAccess.None`, `ForeignAccess.View`, or `ForeignAccess.Edit` (see [Foreign Access](foreign-access.md)) | - -### `[DynamicPropertyUI]` - -Controls property visibility and behavior in the UI: +Use this when the entity itself should support attachments: ````csharp -[DynamicPropertyUI( - DisplayName = "Registration Number", - IsAvailableOnListing = true, - IsAvailableOnDataTableFiltering = true, - CreationFormAvailability = EntityPropertyUIFormAvailability.Hidden, - EditingFormAvailability = EntityPropertyUIFormAvailability.NotAvailable, - QuickLookOrder = 100 +[DynamicEntity] +[DynamicEntityAttachments( + "application/pdf", + "image/png", + MaxFileCount = 3, + MaxFileSizeBytes = 5 * 1024 * 1024, + MaxTotalSizeBytes = 15 * 1024 * 1024 )] -public string RegistrationNumber { get; set; } -```` - -| Property | Type | Default | Description | -|----------|------|---------|-------------| -| `DisplayName` | string | null | Custom label for the property | -| `IsAvailableOnListing` | bool | `true` | Show in data grid | -| `IsAvailableOnDataTableFiltering` | bool | `true` | Show in filter panel | -| `CreationFormAvailability` | enum | `Available` | Visibility on create form | -| `EditingFormAvailability` | enum | `Available` | Visibility on edit form | -| `QuickLookOrder` | int | `-2` | Order in quick-look panel | - -The quick-look panel shows a summary of the selected record: - -![Quick-look panel showing entity details](images/quick-look.png) - -### `[DynamicPropertyServerOnly]` - -Hides a property from API clients entirely. It is stored in the database but never returned to the client: - -````csharp -[DynamicPropertyServerOnly] -public string InternalNotes { get; set; } +public class Product : DynamicEntityBase +{ +} ```` -### `[DynamicPropertySetByClients]` - -Controls whether clients can set this property value. Useful for computed or server-assigned fields: - -````csharp -[DynamicPropertySetByClients(false)] -public string RegistrationNumber { get; set; } -```` +Set `IsEnabled = false` to disable entity attachments explicitly in code. -### `[DynamicPropertyUnique]` +#### `[DynamicEntityCommandInterceptor]` -Marks a property as requiring unique values across all records: - -````csharp -[DynamicPropertyUnique] -public string ProductCode { get; set; } -```` - -### `[DynamicEntityCommandInterceptor]` - -Defines JavaScript interceptors on a class for CRUD lifecycle hooks: +This attribute can be applied multiple times to the same entity: ````csharp [DynamicEntity] [DynamicEntityCommandInterceptor( "Create", InterceptorType.Pre, - "if(!context.commandArgs.data['Name']) { globalError = 'Name is required!'; }" + "if (!context.commandArgs.data['Name']) { globalError = 'Name is required.'; }" )] [DynamicEntityCommandInterceptor( "Delete", InterceptorType.Post, "context.log('Deleted: ' + context.commandArgs.entityId);" )] -public class Organization : DynamicEntityBase +public class Product : DynamicEntityBase { - public string Name { get; set; } + public string Name { get; set; } = null!; } ```` -> The `Name` parameter must be one of: `"Create"`, `"Update"`, or `"Delete"`. The `InterceptorType` can be `Pre`, `Post`, or `Replace`. When `Replace` is used, the default DB operation is skipped entirely and only the JavaScript handler runs. **`Replace-Create` must return the new entity's Id** (e.g. `return result.Id;` after `db.insert`). Multiple interceptors can be added to the same class (`AllowMultiple = true`). - -See [Interceptors](interceptors.md) for the full JavaScript context API. +Use `Create`, `Update`, or `Delete` for `Name`, and `Pre`, `Post`, or `Replace` for `Type`. See [Interceptors](interceptors.md) for the full scripting context and replace-mode behavior. -### `[DynamicEnum]` +#### `[DynamicEnum]` -Marks an enum for use in dynamic entity properties: +Decorate CLR enums that should be visible to the low-code model: ````csharp [DynamicEnum] -public enum OrganizationType +public enum ProductStatus { - Corporate = 0, - Enterprise = 1, - Startup = 2, - Consulting = 3 + Draft = 0, + Active = 1, + Discontinued = 2 } ```` -Reference in an entity: +Then use the enum directly on a dynamic entity property: ````csharp [DynamicEntity] -[DynamicEntityUI(PageTitle = "Organizations")] -public class Organization : DynamicEntityBase +public class Product : DynamicEntityBase { - public string Name { get; set; } - public OrganizationType OrganizationType { get; set; } + public ProductStatus Status { get; set; } } ```` -### Enum Localization - -Enum values can be localized using ABP's localization system. Add localization keys in the format `Enum:{EnumTypeName}.{ValueName}` to your localization JSON files: +Enum localization follows the usual ABP pattern: ```json { "culture": "en", "texts": { - "Enum:OrganizationType.Corporate": "Corporate", - "Enum:OrganizationType.Enterprise": "Enterprise", - "Enum:OrganizationType.Startup": "Startup", - "Enum:OrganizationType.Consulting": "Consulting" + "Enum:ProductStatus.Draft": "Draft", + "Enum:ProductStatus.Active": "Active", + "Enum:ProductStatus.Discontinued": "Discontinued" } } ``` -The React runtime automatically uses these localization keys for enum dropdowns and display values. If no localization key is found, the enum member name is used as-is. +### Property-Level Attributes -## Fluent API +| Attribute | Use it for | Key members | +|-----------|------------|-------------| +| `[DynamicPropertyUI]` | Sets the property display name | `DisplayName` | +| `[Display(Name = ...)]` | Sets the property display name with standard .NET metadata | `Name` | +| `[DynamicPropertyType]` | Overrides the inferred low-code type | `Type` | +| `[DynamicPropertyDefaultValue]` | Sets the descriptor default value | `DefaultValue` | +| `[DynamicPropertyNotMapped]` | Stores the property in the data dictionary instead of a dedicated DB field | No properties | +| `[DynamicForeignKey]` | Configures a lookup relation | `EntityName`, `DisplayPropertyName`, `Access`, `DependsOnPropertyName`, `DependsOnFilterPropertyName` | +| `[DynamicPropertySetByClients]` | Controls whether clients may write the field | `Allow` | +| `[DynamicPropertyServerOnly]` | Hides the field from clients entirely | No properties | +| `[DynamicPropertyUnique]` | Marks the field as unique | No properties | +| `[DynamicPropertyFileOptions]` | Marks the field as a file and applies upload constraints | `MaxSizeBytes`, `AllowedContentTypes` | +| `[DynamicPropertyImageOptions]` | Marks the field as an image and applies upload and resize constraints | `MaxSizeBytes`, `MaxWidth`, `MaxHeight`, `ResizeMode`, `AllowedContentTypes` | -The Fluent API has the **highest priority** in the configuration system. Use `AbpDynamicEntityConfig.EntityConfigurations` to override any attribute or JSON setting programmatically. +#### Display Names: `[DynamicPropertyUI]` and `[Display]` -### Basic Usage - -Configure in startup initialization code (for example `MyAppLowCodeInitializer`): +Both attributes write to the same `DisplayName` field in the descriptor: ````csharp -public static class MyAppLowCodeInitializer -{ - private static readonly AsyncOneTimeRunner Runner = new(); - - public static async Task InitializeAsync() - { - await Runner.RunAsync(async () => - { - AbpDynamicEntityConfig.EntityConfigurations.Configure( - "MyApp.Products.Product", - entity => - { - entity.DefaultDisplayPropertyName = "Name"; - - var priceProperty = entity.AddOrGetProperty("Price"); - priceProperty.AsRequired(); - priceProperty.UI = new EntityPropertyUIDescriptor - { - DisplayName = "Unit Price", - CreationFormAvailability = EntityPropertyUIFormAvailability.Available - }; - - entity.AddOrGetProperty("InternalNotes").AsServerOnly(); - } - ); +[DynamicPropertyUI(DisplayName = "SKU")] +public string Code { get; set; } = null!; - await DynamicModelManager.Instance.InitializeAsync(); - }); - } -} +[Display(Name = "Unit Price")] +public decimal Price { get; set; } ```` -You can also use the generic overload with a type parameter: +If both are present on the same property, `[Display(Name = ...)]` takes precedence. + +Like `DynamicEntityUI`, `DynamicPropertyUI` does **not** control list visibility, form placement, filters, quick-look order, tabs, or other runtime screen layout details. Those belong to page and form descriptors. + +#### Type, Storage, Relations, and Upload Options ````csharp -AbpDynamicEntityConfig.EntityConfigurations.Configure(entity => +public class Product : DynamicEntityBase { - entity.DefaultDisplayPropertyName = "Name"; -}); + [DynamicPropertyType(EntityPropertyType.Money)] + [DynamicPropertyDefaultValue("0")] + public decimal Price { get; set; } + + [DynamicForeignKey( + "Catalog.Categories.Category", + "Name", + ForeignAccess.View + )] + public Guid? CategoryId { get; set; } + + [DynamicForeignKey( + "Catalog.Products.Product", + "Name", + ForeignAccess.View, + DependsOnPropertyName = nameof(CategoryId), + DependsOnFilterPropertyName = "CategoryId" + )] + public Guid? RelatedProductId { get; set; } + + [DynamicPropertyNotMapped] + public string? SearchSummary { get; set; } + + [DynamicPropertySetByClients(false)] + public string? GeneratedCode { get; set; } + + [DynamicPropertyServerOnly] + public string? InternalNotes { get; set; } + + [DynamicPropertyUnique] + public string Code { get; set; } = null!; + + [DynamicPropertyFileOptions( + "application/pdf", + MaxSizeBytes = 5 * 1024 * 1024 + )] + public string? SpecSheet { get; set; } + + [DynamicPropertyImageOptions( + "image/png", + "image/jpeg", + MaxWidth = 1024, + MaxHeight = 1024, + MaxSizeBytes = 2 * 1024 * 1024, + ResizeMode = "fit" + )] + public string? HeroImage { get; set; } +} ```` -### Entity Configuration +`DynamicPropertyFileOptions` sets `Type = File`. `DynamicPropertyImageOptions` sets `Type = Image`. Use them instead of setting file or image types manually when you also need upload constraints. -The `Configure` method provides an `EntityDescriptor` instance. You can set its properties directly: +For image fields, `ResizeMode` currently supports these values: -| Property / Method | Description | -|--------|-------------| -| `DefaultDisplayPropertyName` | Set the display property for lookups | -| `Parent` | Set parent entity name for nesting | -| `UI` | Set entity-level UI (`EntityUIDescriptor` with `PageTitle`) | -| `AddOrGetProperty(name)` | Get or create a property descriptor for configuration | -| `FindProperty(name)` | Find a property descriptor by name (returns `null` if not found) | -| `GetProperty(name)` | Get a property descriptor by name (throws if not found) | -| `Interceptors` | List of `CommandInterceptorDescriptor` — add interceptors directly | +* `fit`: preserves aspect ratio and scales the image down so it fits within `MaxWidth` and `MaxHeight` +* `fill`: crops from the center and scales the image to fill the target box; use it when both `MaxWidth` and `MaxHeight` are set -### Property Configuration +If `ResizeMode = "fill"` is configured without both `MaxWidth` and `MaxHeight`, the current React runtime falls back to `fit`. -`AddOrGetProperty` returns an `EntityPropertyDescriptor`. Configure it using direct property assignment and extension methods: +Resize is currently applied client-side by the React low-code runtime form before upload. Backend upload endpoints validate file size and content type, then store the stream as-is. If you upload images through scripting or direct API/backend calls instead of the React runtime form, no automatic resize is applied on the server. -| Property / Extension Method | Description | -|--------|-------------| -| `.AsRequired(bool)` | Mark as required (extension method, returns the descriptor for chaining) | -| `.AsServerOnly(bool)` | Hide from clients (extension method, returns the descriptor for chaining) | -| `.MapToDbField(bool)` | Control if property is stored in DB (extension method, returns the descriptor for chaining) | -| `.IsUnique` | Set to `true` to mark as unique | -| `.AllowSetByClients` | Set to `false` to prevent client writes | -| `.ForeignKey` | Set a `ForeignKeyDescriptor` to configure foreign key relationship | -| `.UI` | Set an `EntityPropertyUIDescriptor` to configure property UI | +## Standard .NET Attributes and Required Inference -### Chaining Extension Methods +Code-defined low-code properties also consume standard .NET metadata: -The extension methods `AsRequired()`, `AsServerOnly()`, and `MapToDbField()` return the property descriptor, enabling fluent chaining: +* `[Display(Name = ...)]` sets the descriptor `DisplayName` +* any `ValidationAttribute` on the CLR property is copied into the descriptor +* `[Required]` and non-nullable types contribute to `IsRequired` -````csharp -entity.AddOrGetProperty("InternalNotes") - .AsServerOnly() - .AsRequired() - .MapToDbField(); -```` +The required-state rules are: -### Configuring Foreign Keys +* `[Required]` always makes the property required +* non-nullable value types such as `int`, `Guid`, `DateTime`, `decimal`, and `bool` are treated as required +* nullable value types such as `int?` and `Guid?` are optional +* nullable reference types such as `string?` are optional +* non-nullable reference types without an explicit `[Required]` stay optional for backward compatibility -````csharp -AbpDynamicEntityConfig.EntityConfigurations.Configure( - "MyApp.Orders.Order", - entity => - { - var customerIdProperty = entity.AddOrGetProperty("CustomerId"); - customerIdProperty.ForeignKey = new ForeignKeyDescriptor - { - EntityName = "MyApp.Customers.Customer", - DisplayPropertyName = "Name", - Access = ForeignAccess.Edit - }; - } -); -```` +For source-controlled low-code models, the built-in validation set that round-trips cleanly through the descriptor pipeline is: -### Adding Interceptors +* `[Required]` +* `[StringLength]` +* `[MaxLength]` +* `[MinLength]` +* `[Range]` +* `[EmailAddress]` +* `[Phone]` +* `[Url]` +* `[CreditCard]` +* `[RegularExpression]` + +Example: ````csharp -entity.Interceptors.Add(new CommandInterceptorDescriptor("Create") +public class Product : DynamicEntityBase { - Type = InterceptorType.Pre, - Javascript = "if(!context.commandArgs.data['Name']) { globalError = 'Name is required!'; }" -}); + [Required] + [StringLength(128, MinimumLength = 3)] + public string Name { get; set; } = null!; + + [Range(0, 100000)] + public decimal Price { get; set; } + + [EmailAddress] + public string? ContactEmail { get; set; } +} ```` -## Assembly Registration +For advanced validation scenarios, JSON `validators` and cross-field validations are still the better fit than custom CLR validation attributes. + +## Fluent API + +The Fluent API is the highest-priority model layer. Use it when you need runtime overrides, source-controlled patches over descriptor files, or descriptor-only properties without adding CLR members. + +### Registration and Initialization -Register assemblies containing `[DynamicEntity]` classes in startup initialization code: +Register source assemblies before initialization: ````csharp AbpDynamicEntityConfig.SourceAssemblies.Add( new DynamicEntityAssemblyInfo( typeof(MyDomainModule).Assembly, - rootNamespace: "MyApp", - projectRootPath: sourcePath // For descriptor hot-reload + rootNamespace: "Catalog", + projectRootPath: sourcePath ) ); -```` -| Parameter | Description | -|-----------|-------------| -| `assembly` | The assembly containing `[DynamicEntity]` classes and/or descriptor metadata | -| `rootNamespace` | Root namespace for the assembly (used for embedded resource lookup) | -| `projectRootPath` | Path to the Domain project source folder (enables descriptor hot-reload in development) | +await DynamicModelManager.Instance.InitializeAsync(); +```` -You can also register entity types directly: +You can also register specific types directly: ````csharp AbpDynamicEntityConfig.DynamicEntityTypes.Add(typeof(Product)); -AbpDynamicEntityConfig.DynamicEnumTypes.Add(typeof(OrganizationType)); +AbpDynamicEntityConfig.DynamicEnumTypes.Add(typeof(ProductStatus)); ```` -## Combining with JSON Descriptors - -Attributes and JSON descriptors work together seamlessly. A common pattern: - -1. **Define core entities** with C# attributes (compile-time safety) -2. **Add additional entities** via descriptor files (no recompilation needed) -3. **Fine-tune configuration** with Fluent API (overrides everything) - -The three-layer system merges all definitions: - -``` -Fluent API (highest) > JSON descriptors > Code (Attributes) > Defaults (lowest) -``` - -For example, if an attribute sets `[DynamicPropertyUnique]` and a descriptor sets `"isUnique": false`, the JSON value wins because the JSON descriptor layer has higher priority than the Code layer. - -## End-to-End Example - -A complete e-commerce-style entity setup: +Use the generic overload when a CLR type exists, or the string overload for descriptor-only entities: ````csharp -// Enum -[DynamicEnum] -public enum OrderStatus -{ - Pending = 0, - Processing = 1, - Shipped = 2, - Delivered = 3 -} - -// Customer entity -[DynamicEntity] -[DynamicEntityUI(PageTitle = "Customers")] -public class Customer : DynamicEntityBase -{ - [DynamicPropertyUnique] - public string Name { get; set; } - - [DynamicPropertyUI(DisplayName = "Phone Number", QuickLookOrder = 100)] - public string Telephone { get; set; } - - [DynamicForeignKey("Volo.Abp.Identity.IdentityUser", "UserName")] - public Guid? UserId { get; set; } - - [DynamicPropertyServerOnly] - public string InternalNotes { get; set; } -} - -// Product entity -[DynamicEntity] -[DynamicEntityUI(PageTitle = "Products")] -public class Product : DynamicEntityBase +AbpDynamicEntityConfig.EntityConfigurations.Configure(entity => { - [DynamicPropertyUnique] - public string Name { get; set; } + entity.WithDisplayName("Products"); +}); - public decimal Price { get; set; } - public int StockCount { get; set; } -} +AbpDynamicEntityConfig.EntityConfigurations.Configure( + "Catalog.Products.Product", + entity => + { + entity.WithDisplayName("Products"); + } +); +```` -// Order entity with child OrderLine -[DynamicEntity] -[DynamicEntityUI(PageTitle = "Orders")] -[DynamicEntityCommandInterceptor( - "Update", - InterceptorType.Pre, - @"if(context.commandArgs.data['IsDelivered']) { - if(!context.currentUser.roles.includes('admin')) { - globalError = 'Only admins can mark as delivered!'; - } - }" -)] -public class Order : DynamicEntityBase -{ - [DynamicForeignKey("MyApp.Customers.Customer", "Name", ForeignAccess.Edit)] - public Guid CustomerId { get; set; } +### `EntityDescriptor` Surface + +The `Configure(...)` callback gives you an `EntityDescriptor`. + +| Member | What it controls | +|--------|-------------------| +| `DisplayName` | Entity display name | +| `DefaultDisplayPropertyName` | Field used for lookups and relation labels | +| `Parent` | Parent entity name for child entities | +| `Attachments` | Raw `EntityAttachmentDescriptor` access | +| `CrossFieldValidations` | Raw cross-field validation list | +| `Interceptors` | Raw interceptor list | +| `Properties` | Full property descriptor list | +| `AddOrGetProperty(name)` | Returns an existing property or creates a new descriptor | +| `FindProperty(name)` | Returns the property or `null` | +| `GetProperty(name)` | Returns the property or throws | +| `WithDisplayName(string)` | Fluent helper for `DisplayName` | +| `EnableAttachments(...)` | Fluent helper for attachment configuration | +| `DisableAttachments()` | Explicitly disables attachments | +| `AddCrossFieldValidation(...)` | Adds an entity-level cross-field validation | + +### `EntityPropertyDescriptor` Surface + +`AddOrGetProperty(...)`, `FindProperty(...)`, and `GetProperty(...)` work with `EntityPropertyDescriptor`. + +#### Direct members + +| Member | What it controls | +|--------|-------------------| +| `DisplayName` | Property display label | +| `Type` | Low-code property type | +| `IsRequired` | Required state | +| `IsMappedToDbField` | Dedicated DB field vs data dictionary storage | +| `DefaultValue` | Default value stored in the descriptor | +| `IsUnique` | Uniqueness | +| `AllowSetByClients` | Client write access | +| `ServerOnly` | Hide from clients entirely | +| `ForeignKey` | Foreign key descriptor | +| `EnumType` | Enum CLR type name for descriptor-only enum fields | +| `FileMaxSizeBytes` | File/image max size | +| `FileAllowedContentTypes` | Allowed MIME types for file/image fields | +| `ImageMaxWidth` | Image width constraint | +| `ImageMaxHeight` | Image height constraint | +| `ImageResizeMode` | Resize strategy | +| `ValidationAttributes` | Raw validation descriptors | + +#### Extension methods + +| Method | What it does | +|--------|---------------| +| `MapToDbField(bool isMappedToDbField = true)` | Sets `IsMappedToDbField` | +| `AsType(EntityPropertyType type)` | Sets `Type` | +| `AsMoney()` | Sets `Type = Money` | +| `AsFile(long? maxSizeBytes = null, params string[] allowedContentTypes)` | Sets `Type = File` and file constraints | +| `AsImage(long? maxSizeBytes = null, int? maxWidth = null, int? maxHeight = null, string? resizeMode = null, params string[] allowedContentTypes)` | Sets `Type = Image` and image constraints | +| `WithDefaultValue(string? defaultValue)` | Sets `DefaultValue` | +| `WithEnumType(string enumType)` | Sets `Type = Enum` and `EnumType` | +| `WithForeignKey(string entityName, string? displayPropertyName = null, ForeignAccess access = ForeignAccess.None, string? dependsOnPropertyName = null, string? dependsOnFilterPropertyName = null)` | Configures the relation in one call | +| `AsServerOnly(bool serverOnly = true)` | Sets `ServerOnly` | +| `AsRequired(bool isRequired = true)` | Sets `IsRequired` | + +### Fluent API Example - public decimal TotalAmount { get; set; } - public bool IsDelivered { get; set; } - public OrderStatus Status { get; set; } -} +````csharp +AbpDynamicEntityConfig.EntityConfigurations.Configure( + "Catalog.Products.Product", + entity => + { + entity.WithDisplayName("Products"); + entity.DefaultDisplayPropertyName = "Name"; + entity.EnableAttachments( + 5, + 5 * 1024 * 1024, + 20 * 1024 * 1024, + "application/pdf", + "image/png" + ); + + entity.AddOrGetProperty("Code") + .AsRequired() + .WithDefaultValue("P-"); + + entity.GetProperty("Code").DisplayName = "SKU"; + + entity.AddOrGetProperty("Price") + .AsMoney() + .AsRequired(); + + entity.GetProperty("Price").DisplayName = "Unit Price"; + + entity.AddOrGetProperty("Status") + .WithEnumType("Catalog.Products.ProductStatus"); + + entity.AddOrGetProperty("CategoryId") + .WithForeignKey("Catalog.Categories.Category", "Name", ForeignAccess.View); + + entity.AddOrGetProperty("HeroImage") + .AsImage( + 2 * 1024 * 1024, + 1024, + 1024, + "fit", + "image/png", + "image/jpeg" + ); -[DynamicEntity(Parent = "MyApp.Orders.Order")] -public class OrderLine : DynamicEntityBase -{ - [DynamicForeignKey("MyApp.Products.Product", "Name")] - public Guid ProductId { get; set; } + entity.AddOrGetProperty("InternalNotes") + .AsServerOnly(); - public int Quantity { get; set; } - public decimal Amount { get; set; } -} -```` + entity.AddOrGetProperty("DiscountedPrice") + .AsMoney() + .WithDefaultValue("0"); -Register everything in startup initialization code: + entity.AddCrossFieldValidation( + "DiscountedPrice", + "Price", + EntityCrossFieldValidationOperators.LessThanOrEqual, + "Discounted price cannot exceed unit price." + ); -````csharp -public static class MyAppLowCodeInitializer -{ - private static readonly AsyncOneTimeRunner Runner = new(); - - public static async Task InitializeAsync() - { - await Runner.RunAsync(async () => + entity.Interceptors.Add(new CommandInterceptorDescriptor("Create") { - // Reference existing ABP entities - AbpDynamicEntityConfig.ReferencedEntityList.Add("UserName"); - - // Register assembly - AbpDynamicEntityConfig.SourceAssemblies.Add( - new DynamicEntityAssemblyInfo(typeof(MyDomainModule).Assembly) - ); - - // Initialize - await DynamicModelManager.Instance.InitializeAsync(); + Type = InterceptorType.Pre, + Javascript = "if (!context.commandArgs.data['Name']) { globalError = 'Name is required.'; }" }); } -} +); ```` -Configure your DbContext to implement `IDbContextWithDynamicEntities`: +### Fluent API Notes + +* Use attributes when the field already exists as a CLR property. +* Use Fluent API when you need to override descriptor values without touching the CLR class. +* Use Fluent API when you need descriptor-only properties or cross-field validations. +* Use JSON descriptors or the designer for page/form/filter/dashboard/menu/page-group metadata. + +## EF Core Setup + +Your DbContext should implement `IDbContextWithDynamicEntities` and call `ConfigureDynamicEntities()`: ````csharp -public class MyAppDbContext : AbpDbContext, IDbContextWithDynamicEntities +public class CatalogDbContext : AbpDbContext, IDbContextWithDynamicEntities { - // ... constructors and DbSets ... - protected override void OnModelCreating(ModelBuilder builder) { - builder.ConfigureDynamicEntities(); base.OnModelCreating(builder); + builder.ConfigureDynamicEntities(); } } ```` -Configure your DbContextFactory for EF Core CLI commands: +Run low-code initialization before EF Core design-time migrations so the model is complete when migrations are generated. -````csharp -public class MyAppDbContextFactory : IDesignTimeDbContextFactory -{ - public MyAppDbContext CreateDbContext(string[] args) - { - var configuration = BuildConfiguration(); - - MyAppEfCoreEntityExtensionMappings.Configure(); - - // ----- Ensure Low-Code system is initialized before running migrations --- - LowCodeEfCoreTypeBuilderExtensions.Configure(); - AsyncHelper.RunSync(MyAppLowCodeInitializer.InitializeAsync); - // ------------------------------- - - var builder = new DbContextOptionsBuilder() - .UseSqlServer(configuration.GetConnectionString("Default")); - - return new MyAppDbContext(builder.Options); - } - - // ... BuildConfiguration method ... -} -```` +## Layer Precedence + +The final model is merged in this order: + +```text +Fluent API > JSON descriptors > Code attributes and CLR metadata > Defaults +``` + +For example: -This gives you four auto-generated pages (Customers, Products, Orders with nested OrderLines), complete with permissions, menu items, foreign key lookups, and interceptor-based business rules. +* if `[DynamicPropertyUnique]` marks a field as unique but a descriptor sets `"isUnique": false`, the descriptor wins +* if JSON sets a display name and Fluent API later changes `DisplayName`, the Fluent API wins ## See Also * [Model Descriptor Files](model-json.md) * [Code Integration](code-integration.md) * [Reference Entities](reference-entities.md) +* [Foreign Access](foreign-access.md) * [Interceptors](interceptors.md) diff --git a/docs/en/low-code/model-json.md b/docs/en/low-code/model-json.md index 4590e0827e..66b5c0486c 100644 --- a/docs/en/low-code/model-json.md +++ b/docs/en/low-code/model-json.md @@ -270,6 +270,15 @@ Use `file` or `image` properties for first-class upload fields: } ``` +`imageResizeMode` currently supports: + +* `fit`: preserve aspect ratio and scale down to fit within `imageMaxWidth` and `imageMaxHeight` +* `fill`: crop from the center and scale to fill the target box + +When `imageResizeMode` is `fill`, set both `imageMaxWidth` and `imageMaxHeight`. If either dimension is missing, the current React runtime falls back to `fit`. + +Image resizing is currently performed client-side by the React low-code runtime before upload. Backend upload endpoints still validate size and content type, but they store the uploaded bytes as-is. Direct API uploads and scripting uploads do not get automatic server-side resizing. + Use entity `attachments` when each record can have multiple arbitrary files: ```json