Skip to main content
.NET 8.0+

DevExpress v25.1 Update — Your Feedback Matters

Our What's New in v25.1 webpage includes product-specific surveys. Your response to our survey questions will help us measure product satisfaction for features released in this major update and help us refine our plans for our next major release.

Take the survey Not interested

Reference Properties in EF Core

  • 2 minutes to read

The example below illustrates how to implement Reference (Foreign Key, Complex Type) Properties in an EF Core class.

using DevExpress.ExpressApp;
using DevExpress.ExpressApp.DC;
using DevExpress.ExpressApp.Editors;
using DevExpress.Persistent.Base;
using DevExpress.Persistent.BaseImpl.EF;
// ...
[DefaultClassOptions]
public class ReferencedPropertiesObject : BaseObject {
    // Displayed in a lookup control: 
    public virtual ReferencedObject LookupReferencedObject { get; set; }
    // Displayed in a set of editors. Each editor represents an individual property of the referenced object: 
    [Aggregated, ExpandObjectMembers(ExpandObjectMembers.Always)]
    public virtual ExpandPropertiesObject ExpandPropertiesObject { get; set; }
    // Displayed in a Detail Property Editor that shows a referenced object's Detail View: 
    [Aggregated, EditorAlias(EditorAliases.DetailPropertyEditor)]
    [ExpandObjectMembers(ExpandObjectMembers.Never)]
    public virtual EmbeddedDetailViewObject EmbeddedDetailViewObject { get; set; }
    // Displayed in a button edit that invokes a referenced object's Detail View in a separate modal window: 
    [Aggregated, ExpandObjectMembers(ExpandObjectMembers.Never)]
    public virtual PopupDetailViewObject PopupDetailViewObject { get; set; }

    public override void OnCreated() {
        EmbeddedDetailViewObject = ObjectSpace.CreateObject<EmbeddedDetailViewObject>();
        ExpandPropertiesObject = ObjectSpace.CreateObject<ExpandPropertiesObject>();
    }
}

// Make sure that you use options.UseChangeTrackingProxies() in your DbContext settings.

Note that reference properties should be declared as virtual in EF.

If you use Detail Property Editor to edit a reference property, or apply the ExpandObjectMembers attribute to a reference property, it is required to initialize such a property when a new parent object is created. Otherwise, the reference property’s fields will be read-only. The initialization should be done in the following way:

The code snippet above demonstrates these steps.

See Also