xaf-efcore-entities
Skill4 starsChanged 6 months agoMITView on GitHub
Author EF Core entities for DevExpress XAF applications. Use when creating, modifying, or reviewing XAF business objects with EF Core. Covers the critical gotchas that silently break XAF: virtual properties, no OwnsOne, BaseObjectInt pattern, collection initialization, decimal precision, aggregated relationships, DbContext registration, Web API exposure, and role permission caveats. Triggers on any XAF EF Core entity work.
In this repository11 other files it gives its agents.
- devexpress-xaf-dockerSkill
- xaf-blazor-startupSkill
- xaf-conditional-appearanceSkill
- xaf-easytest-authoringSkill
- xaf-environment-authSkill
- xaf-hangfire-jobsSkill
- xaf-navigation-hubSkill
- xaf-playwright-testingSkill
- xaf-reportingSkill
- xaf-search-panelsSkill
- xaf-securitySkill
The file
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 42
Use ObservableCollection<T> (not List<T>) for change tracking.
- Very specific: line 50
Do NOT use [Aggregated] on many-to-many or optional references
- Very specific: line 52
When removing items in a loop, use while (col.Count > 0) { col.Remove(col[0]).
- Distinctive: line 67
Always set precision for decimal properties or values get silently truncated.
- Very specific: line 77
Use [NotMapped] properties with [ImmediatePostData] for UI-friendly access (type pickers, enum dropdowns) backed by persistent string …
- Distinctive: line 180
Every new entity needs:
- Very specific: line 226
Use ExcludeFromMigrations() for externally-managed tables (e.g., partitioned tables)
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
XAF EF Core Entity Authoring
Entity Rules (violations fail silently)
All properties MUST be virtual
EF Core change-tracking proxies and XAF's INotifyPropertyChanged require it. Non-virtual properties save without error but changes are silently lost.
// CORRECT
public virtual string Name { get; set; } = string.Empty;
public virtual DateTime Date { get; set; }
public virtual ApplicationUser? User { get; set; }
// WRONG - silently fails to track changes
public string Name { get; set; } = string.Empty;No OwnsOne / owned entity types
XAF EF Core does not support OwnsOne(). Use separate entities with navigation properties instead.
// CORRECT - separate entity
public virtual Address? BillingAddress { get; set; }
// WRONG - XAF will break
// modelBuilder.Entity<Client>().OwnsOne(c => c.BillingAddress);Collections: ObservableCollection with [Aggregated]
Use ObservableCollection<T> (not List<T>) for change tracking. List<T> silently loses collection change events.
[Aggregated]
public virtual IList<ContactPerson> ContactPersons { get; set; } = new ObservableCollection<ContactPerson>();[Aggregated]= cascade delete + children cannot exist without parent- Do NOT use
[Aggregated]on many-to-many or optional references - Non-aggregated nav properties use
DeleteBehavior.SetNullby default - When removing items in a loop, use
while (col.Count > 0) { col.Remove(col[0]); }— neverClear()
Explicit foreign key properties
Declare FK properties explicitly with [ForeignKey] for reliable behavior during nested detail view edits and proxy change detection.
public virtual Guid? CustomClassId { get; set; }
[ForeignKey(nameof(CustomClassId))]
public virtual CustomClass? CustomClass { get; set; }Decimal precision in OnModelCreating
Always set precision for decimal properties or values get silently truncated.
modelBuilder.Entity<TimeEntry>()
.Property(p => p.Hours)
.HasPrecision(18, 2);[NotMapped] computed properties for UI
Use [NotMapped] properties with [ImmediatePostData] for UI-friendly access (type pickers, enum dropdowns) backed by persistent string fields.
[NotMapped]
[TypeConverter(typeof(LocalizedClassInfoTypeConverter))]
[ImmediatePostData]
public Type DataType { get; set; } // UI-friendly
public virtual string DataTypeName { get; set; } // PersistedBaseObjectInt Pattern
For int auto-increment keys (instead of XAF's default Guid BaseObject). Origin: C:\Projects\XafSearch.
public abstract class BaseObjectInt : IXafEntityObject, IObjectSpaceLink
{
protected IObjectSpace ObjectSpace;
[Key]
[VisibleInListView(false)]
[VisibleInDetailView(false)]
[VisibleInLookupListView(false)]
public virtual int ID { get; set; }
IObjectSpace IObjectSpaceLink.ObjectSpace
{
get => ObjectSpace;
set => ObjectSpace = value;
}
public virtual void OnCreated() { }
public virtual void OnSaving() { }
public virtual void OnLoaded() { }
}Essential Attributes
| Attribute | Purpose |
[DefaultClassOptions] | Makes entity visible in XAF navigation |
[DefaultProperty(nameof(Name))] | Display text in lookups and references |
[Aggregated] | Cascade delete for child collections |
[Required] | Standard validation |
[VisibleInListView(false)] | Hide from list views (e.g., ID column) |
[DomainComponent] | Marks non-persistent objects for XAF discovery |
[RuleFromBoolProperty] | Validation via computed bool properties |
EF Core ValueConverter for unsupported types
System.Drawing.Color is not natively storable. Use a ValueConverter:
public class NullableColorToInt32Converter : ValueConverter<Color?, int?>
{
public NullableColorToInt32Converter()
: base(c => c.HasValue ? c.Value.ToArgb() : null,
v => v.HasValue ? Color.FromArgb(v.Value) : null) { }
}
// In OnModelCreating:
entity.Property(e => e.BackColor).HasConversion<NullableColorToInt32Converter>();Unique Indexes with GCRecord filter
For soft-delete compatibility, filter unique constraints to exclude soft-deleted rows:
b.HasIndex(nameof(ClassName)).IsUnique().HasFilter("\"GCRecord\" = 0");Enum Storage
XAF stores enums as strings in the database (e.g., TimeEntryStatus.Draft becomes "Draft"). When bridging to external systems (e.g., SQLite in a mobile app), cast to (int) for storage and back to enum string for OData POST.
EF Core Interceptors with XAF
XAF manages DbContext creation — standard DI-based interceptor registration (AddDbContext<T>(o => o.AddInterceptors(...))) doesn't work. Use a static interceptor list on the DbContext:
// In DbContext class:
public static readonly List<IInterceptor> ExternalInterceptors = new();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
if (ExternalInterceptors.Count > 0)
optionsBuilder.AddInterceptors(ExternalInterceptors);
}Register in Startup.cs before services.AddXaf(...):
MyDbContext.ExternalInterceptors.Add(new MyMetricsInterceptor());Common use cases: query duration metrics (DbCommandInterceptor), audit logging, soft-delete filtering.
DbContext Checklist
Every new entity needs:
DbSet<T>property in the DbContext- Decimal precision in
OnModelCreating(if applicable) - Web API registration in
Startup.csif exposed via OData — missing = 404 AdditionalExportedTypes.Add(typeof(T))in Module if not auto-discovered
OnModelCreating Boilerplate
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.UseDeferredDeletion(this);
modelBuilder.UseOptimisticLock();
modelBuilder.SetOneToManyAssociationDeleteBehavior(DeleteBehavior.SetNull, DeleteBehavior.Cascade);
modelBuilder.HasChangeTrackingStrategy(
ChangeTrackingStrategy.ChangingAndChangedNotificationsWithOriginalValues);
modelBuilder.UsePropertyAccessMode(PropertyAccessMode.PreferFieldDuringConstruction);
// ... entity-specific configuration
}PostgreSQL-specific
DateTime / Npgsql UTC trap (CRITICAL)
Npgsql 6+ enforces strict DateTimeKind semantics. XAF generates DateTime values with DateTimeKind.Unspecified throughout its internals (audit trails, model diffs, security timestamps, and your own entities). Npgsql rejects these for timestamp with time zone columns with:
Cannot write DateTime with Kind=Unspecified to PostgreSQL type 'timestamp with time zone'This affects ALL DateTime properties — your entities, XAF system tables, and internal infrastructure. The app may crash on startup before your code even runs.
Fix: Set the legacy switch in Program.cs BEFORE creating the host builder:
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
// Then: var builder = WebApplication.CreateBuilder(args);This forces Npgsql to treat all timestamps as timezone-naive, matching XAF's DateTime semantics. Without it, even basic operations like loading security roles or writing model diffs will throw.
Other PostgreSQL notes
- Use
ExcludeFromMigrations()for externally-managed tables (e.g., partitioned tables) - XAF connection strings use
EFCoreProvider=PostgreSql;prefix — strip it when passing to non-XAF consumers (e.g., Hangfire):var cleaned = Regex.Replace(connStr, @"EFCoreProvider\s*=\s*[^;]+;\s*", "", RegexOptions.IgnoreCase); - XAF Model Editor always tries to load
Microsoft.EntityFrameworkCore.SqlServerat design time, even with PostgreSQL. Add it as a design-time-only reference to avoid Model Editor errors.
Type Storage
Store Type.FullName (not AssemblyQualifiedName) — AQN breaks on every recompilation due to assembly version changes. Resolve via XafTypesInfo.Instance.FindTypeInfo(name)?.Type with fallback to Type.GetType(name).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

