agentleFS
MBrekhofMBrekhof/xafskills/skills/xaf-efcore-entities/SKILL.md

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.

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
  1. Very specific:

    Use ObservableCollection<T> (not List<T>) for change tracking.

    line 42
  2. Very specific:

    Do NOT use [Aggregated] on many-to-many or optional references

    line 50
  3. Very specific:

    When removing items in a loop, use while (col.Count > 0) { col.Remove(col[0]).

    line 52
  4. Distinctive:

    Always set precision for decimal properties or values get silently truncated.

    line 67
  5. Very specific:

    Use [NotMapped] properties with [ImmediatePostData] for UI-friendly access (type pickers, enum dropdowns) backed by persistent string …

    line 77
  6. Distinctive:

    Every new entity needs:

    line 180
  7. Very specific:

    Use ExcludeFromMigrations() for externally-managed tables (e.g., partitioned tables)

    line 226

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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.SetNull by default
  • When removing items in a loop, use while (col.Count > 0) { col.Remove(col[0]); } — never Clear()

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; }  // Persisted

BaseObjectInt 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

AttributePurpose
[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:

  1. DbSet<T> property in the DbContext
  2. Decimal precision in OnModelCreating (if applicable)
  3. Web API registration in Startup.cs if exposed via OData — missing = 404
  4. 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.SqlServer at 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).

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.