Skip to main content
A newer version of this page is available. .
All docs
V21.2
.NET Framework 4.5.2+

Use the Entity Framework Core Data Model

  • 4 minutes to read

This topic describes how to use the Entity Framework Core (EF Core) business model created within the DbContext entity container in XAF.

Read Tutorial: Business Model Design with Entity Framework Core

Specify the Entity Container (Context)

In the Entity Framework Core, the DbContext is used to create and manage data. In XPO, there is a Session class that has the same functions.

File: MySolution.Module\BusinessObjects\MySolutionDbContext.cs

using DevExpress.ExpressApp.Design;
using DevExpress.ExpressApp.EFCore.DesignTime;
using DevExpress.ExpressApp.EFCore.Updating;
using Microsoft.EntityFrameworkCore;
// ...
public class MySolutionContextInitializer : DbContextTypesInfoInitializerBase {
    protected override DbContext CreateDbContext() {
        var builder = new DbContextOptionsBuilder<MySolutionEFCoreDbContext>()
            .UseSqlServer(@";");
        return new MySolutionEFCoreDbContext(builder.Options);
    }
}
[TypesInfoInitializer(typeof(MySolutionContextInitializer))]
public class MySolutionEFCoreDbContext : DbContext {
    public MySolutionEFCoreDbContext(DbContextOptions<MySolutionEFCoreDbContext> options) : base(options) { }
    public DbSet<ModuleInfo> ModulesInfo { get; set; }
    // ...
}

In XAF, an Object Space is used to manipulate data provided by a particular data layer. Generally, Object Space implements an IObjectSpace interface and wraps over the DbContext if Entity Framework Core is used, or the Session if XPO is used. To allow an application to use EFCoreObjectSpace to access application data, the Solution Wizard adds EFCoreObjectSpaceProvider to the ObjectSpaceProviders collection in the application’s CreateDefaultObjectSpaceProvider method.

WinForms

File: MySolution.Win\WinApplication.cs.

using DevExpress.ExpressApp.EFCore;
// ...
public partial class MySolutionWinApplication : WinApplication {
    // ...
    protected override void CreateDefaultObjectSpaceProvider(CreateCustomObjectSpaceProviderEventArgs args) {
        var efCoreObjectSpaceProvider = new EFCoreObjectSpaceProvider(typeof(EFCoreDemoDbContext), TypesInfo, args.ConnectionString,
            (builder, connectionString) => { builder.UseSqlServer(connectionString); });
        args.ObjectSpaceProviders.Add(efCoreObjectSpaceProvider);
        // ...
    }
}

ASP.NET Core Blazor

File: MySolution.Blazor.Server\BlazorApplication.cs.

using DevExpress.ExpressApp.EFCore;
// ...
public partial class MySolutionBlazorApplication : BlazorApplication {
    // ...
    protected override void CreateDefaultObjectSpaceProvider(CreateCustomObjectSpaceProviderEventArgs args) {
        IDbContextFactory<MySolutionEFCoreDbContext> dbFactory = 
            ServiceProvider.GetService<IDbContextFactory<MySolutionEFCoreDbContext>>();
        EFCoreObjectSpaceProvider efCoreObjectSpaceProvider = 
            new EFCoreObjectSpaceProvider(dbFactory, TypesInfo);
        args.ObjectSpaceProviders.Add(efCoreObjectSpaceProvider);
        // ...
    }
}

File: MySolution.Blazor.Server\Startup.cs.

public class Startup {
    // ...
    public void ConfigureServices(IServiceCollection services) {
        // ...
        services.AddDbContextFactory<MySolutionEFCoreDbContext>((serviceProvider, options) => {
            string connectionString = Configuration.GetConnectionString("ConnectionString");
            options.UseSqlServer(connectionString);
            options.UseLazyLoadingProxies();
            // ...
        }, ServiceLifetime.Scoped);
    }
}

Specify the Database Connection

Important

The Security System requires Multiple Active Result Sets in EF Core-based applications connected to the MSSql database. We do not recommend that you remove “MultipleActiveResultSets=True;“ from the connection string or set the MultipleActiveResultSets parameter to false.

WinForms

In WinForms applications, the database connection can be specified via one of the following (see Connect an XAF Application to a Database Provider).

  • The ConnectionString attribute in the configuration file (MySolution.Win\App.config).

    <?xml version="1.0"?>
    <configuration>
      <!-- ... -->
      <connectionStrings>
          <add name="ConnectionString" connectionString="Integrated Security=SSPI;MultipleActiveResultSets=True;Data Source=(localdb)\mssqllocaldb;Initial Catalog=Solution111" providerName="System.Data.SqlClient" />
          <!-- ... -->
      </connectionStrings>
    </configuration>
    
  • The XafApplication.ConnectionString property in the MySolution.Win\Program.cs file.

    static class Program {
        [STAThread]
        static void Main() {
            // ...
            MySolutionWindowsFormsApplication winApplication = new MySolutionWindowsFormsApplication();
            if(ConfigurationManager.ConnectionStrings["ConnectionString"] != null) {
                winApplication.ConnectionString = 
                ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            }
            // ...
        }
    }
    

ASP.NET Core Blazor

In ASP.NET Core Blazor applications, the database connection can be specified in the ConnectionString section in the configuration file (MySolution.Blazor.Server\appsettings.json):

{
  "ConnectionStrings": {
    "ConnectionString": "Integrated Security=SSPI;Pooling=false;MultipleActiveResultSets=True;Data Source=(localdb)\\mssqllocaldb;Initial Catalog=MySolution",
    // ...
  },
  // ...
}

Add Entities to the UI

To display your entities in the Navigation System, follow the steps below.

  1. Add the DefaultClassOptionsAttribute or NavigationItemAttribute to their implementations. To hide key properties from the UI, apply Browsable(false) attributes to them. You can apply other built-in attributes as well.

    using DevExpress.Persistent.Base;
    using System;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    // ...
    [DefaultClassOptions]
    public class Contact : INotifyPropertyChanged {
        [Browsable(false)]
        public Int32 ContactId { get; protected set; }
        private String fullName;
        public String FullName {
            get { return fullName; }
            set {
                if(fullName != value) {
                    fullName = value;
                    OnPropertyChanged();
                }
            }
        }
        // ...
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null) {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    
  2. Add the new entity to the solution’s DbContext in the MySolution.Module\BusinessObjects\MySolutionDbContext.cs file.

    using Microsoft.EntityFrameworkCore;
    // ...
    public class MySolutionEFCoreDbContext : DbContext {
        public MySolutionEFCoreDbContext(DbContextOptions<MySolutionEFCoreDbContext> options) : base(options) { }
        // ...
        public DbSet<Contact> Contacts { get; set; }
    }
    

You can review the EFCoreDemo.Blazor demo application that ship with XAF. This demo is installed to the following folder: %PUBLIC%\Documents\DevExpress Demos 21.2\Components\eXpressApp Framework\EFCoreDemo.

See Also