Skip to main content
A newer version of this page is available. .

Bind Components to Data with Entity Framework Core

  • 3 minutes to read

Entity Framework Core (EF) is a data access technology. EF uses a model to access data. The model consists of entity classes and a context object that stores information about a connection session with the database.

You can use EF to fetch data from the database to DevExpress components, for example, Data Grid. To do this, follow the steps below:

  1. Create a Blazor Server project from a Microsoft or DevExpress template.

  2. Add EF NuGet packages EF to your project.

  3. Create a model for an exiting database. To do this, use Scaffold-DbContext command. In Visual Studio, select ToolsNuGet Package MangerPackage Manger Console and run the following command:

    Scaffold-DbContext "Server=.; Database=NWind; Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables Categories
    

    The command above gets the connection string required to connect to the database. Then, the command obtains DbContext and creates entity classes for the NWind database’s Categories table and the context class.

    For more information about scaffolding, refer to the MSDN documentation or use the following command in the Package Manager console: get-help scaffold-dbcontext –detailed.

  4. Register the scaffolded DbContext in the Startup.cs file:

    //...
    public void ConfigureServices(IServiceCollection services)
    {
        //...
        services.AddDbContext<NWindContext>();
    }
    //...
    
  5. Add EntityFrameworkCore and the generated class namespaces to the Razor page’s using section. Additionally, inject the database context into the Blazor page layout:

    @using Microsoft.EntityFrameworkCore
    @using Project.Models
    @inject NWindContext DataBaseContext
    
  6. Load data from the context:

    List<Category> data = new List<Category>();
    protected override async Task OnInitializedAsync() {
        // Implement read operation
        data = DataBaseContext.Categories.ToList();
        await base.OnInitializedAsync();
    }
    
  7. Add a DevExpress Data Grid to the page layout. Bind the component to data:

    <DxDataGrid Data="@data">
        <Columns>
            <DxDataGridCommandColumn Width="100px" />
            <DxDataGridColumn Field="@nameof(Category.CategoryId)"></DxDataGridColumn>
            <DxDataGridColumn Field="@nameof(Category.CategoryName)"></DxDataGridColumn>
            <DxDataGridColumn Field="@nameof(Category.Description)"></DxDataGridColumn>
        </Columns>
    </DxDataGrid>
    

    Run the project. The Data Grid grid displays data from the bound data source. Data Grid with Data Obtained with EF

  8. Implement the Create, Update and Delete operations. To do this, handle the corresponding events and update the data source.

    @using Microsoft.EntityFrameworkCore
    @using DxBlazorApplication1.Models
    @using DxBlazorApplication1.Controllers
    
    @inject NWindContext DataBaseContext
    
    <DxDataGrid Data="@data"
                RowInserting="@((dataItem) => OnRowInserting(dataItem))"
                RowUpdating="@((dataItem, newValues) => OnRowUpdating(dataItem, newValues))"
                RowRemoving="@OnRowRemoving">
        <Columns>
            <DxDataGridCommandColumn Width="100px" />
            <DxDataGridColumn Field="@nameof(Category.CategoryId)"></DxDataGridColumn>
            <DxDataGridColumn Field="@nameof(Category.CategoryName)"></DxDataGridColumn>
            <DxDataGridColumn Field="@nameof(Category.Description)"></DxDataGridColumn>
        </Columns>
    </DxDataGrid>
    
    @code {
    
        List<Category> data = new List<Category>();
    
        protected override async Task OnInitializedAsync() {
            data = DataBaseContext.Categories.ToList();
            await base.OnInitializedAsync();
        }
    
        Category FillItem(Category dataItem, Dictionary<string, object> itemProperties) {
            dataItem.CategoryName = (string)itemProperties[nameof(Category.CategoryName)];
            dataItem.Description = (string)itemProperties[nameof(Category.Description)];
            return dataItem;
        }
    
        void OnRowInserting(Dictionary<string, object> newValues) {
            Category dataItem = FillItem(new Category(), newValues);
            DataBaseContext.Categories.Add(dataItem);
            DataBaseContext.SaveChanges();
            data = DataBaseContext.Categories.ToList();
            StateHasChanged();
        }
    
        void OnRowUpdating(Category dataItem, Dictionary<string, object> newValues) {
            dataItem = FillItem(dataItem, newValues);
            DataBaseContext.Entry(dataItem).State = EntityState.Modified;
            DataBaseContext.SaveChanges();
            data = DataBaseContext.Categories.ToList();
            StateHasChanged();
        }
    
        void OnRowRemoving(Category dataItem) {
            var todoItem = DataBaseContext.Categories.Find(dataItem.CategoryId);
            DataBaseContext.Categories.Remove(todoItem);
            DataBaseContext.SaveChanges();
            data = DataBaseContext.Categories.ToList();
            StateHasChanged();
        }
    }
    

Note

Blazor WebAssembly prevents most of the direct connections and requests to databases. If you use a WASM Blazor application, you should have a separate application for database operations. For more information, refer to the Blazor documentation or our GitHub example.

Run Demo: Data Grid - Data Binding Run Demo: Data Grid - Edit Data