Steps to reproduce:
- Create the following data model with a custom reference type key (not auto-generated):
C#[DefaultProperty(nameof(Symbol))]
public class VatRate
{
[FieldSize(3)]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public virtual string Symbol { get; set; }
}
- Call the IObjectSpace.CreateObject method for this data model or create this data model via XAF's UI (the New Object Action):
C#vat = ObjectSpace.CreateObject<VatRate>(); vat.Symbol = symbol;
Current results:
System.InvalidOperationException HResult=0x80131509 Message=Unable to track an entity of type 'VatRate' because its primary key property 'Symbol' is null. Source=Microsoft.EntityFrameworkCore StackTrace: at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NullableKeyIdentityMap`1.Add(InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties) …
Expected results:
- A CreateObject method overload that accepts initialization logic, similar to what EF Core has.
- A way to override object creation via XAF's UI (for instance, via an event handler or a virtual method in the NewObjectViewController class).
- Our backend Web API Service also allows to create new VatRate objects via endpoints.
Workarounds
- Inheritance from our BaseObject or a custom auto-generated System.Guid or Int32/Int64 key can be a workaround. You can also create a unique index for your Symbol column in this case: https://learn.microsoft.com/en-us/ef/core/modeling/indexes?tabs=data-annotations#index-uniqueness.
- More complex workarounds include implementing a custom EFCoreObjectSpace.