Seeking Guidance for Getting Started with Blazor Server, EF Core, and SQLite

Yusuf 791 Reputation points
2023-08-30T15:36:48.0666667+00:00

Hello,

I'm new to the world of web development and eager to learn. I've been looking into Blazor Server, EF Core (specifically using the Code First approach), and SQLite as technologies to kickstart my journey. My goal is to create a basic application that can display a list of simple names retrieved from an SQLite database using EF Core's Code First approach within a Blazor Server application.

While researching online, I've come across various approaches, but I'm aiming for a clean and organized method to get started, especially focusing on the Code First aspect of EF Core. Can you provide guidance and perhaps a code example on how to build this kind of beginner-friendly application? I believe having a clear example will significantly help me understand these technologies better and set me on the right path.

Thank you for your valuable assistance!

Developer technologies | .NET | Entity Framework Core
Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Blazor
{count} votes

Accepted answer
  1. Qing Guo - MSFT 896 Reputation points Microsoft External Staff
    2023-08-31T05:32:13.88+00:00

    Hi @Yusuf,

    Can you provide guidance and perhaps a code example on how to build

    Below is a work demo, you can refer to it.

    1.Add the NuGet Packages:

     Microsoft.EntityFrameworkCore.Sqlite
    
     Microsoft.EntityFrameworkCore.Tools
    

    2.Add the following classes into Data directory:

    Product.cs: This is the product class that represent the Product Entity.

     public class Product
     {
         public int Id { get; set; }
         public string Name { get; set; }
        
     }
    

    ProductDbContext.cs:

     public class ProductDbContext : DbContext
     {
        
         public ProductDbContext(DbContextOptions<ProductDbContext> options)
                 : base(options)
         {
         }
     
         public DbSet<Product> Product { get; set; }
    
     }
    

    ProductServices.cs: This is the service class that uses the ProductDbContext class internally and provide 4 methods to create, read, update and delete products from the context.

    public class ProductServices
    {
      
        private ProductDbContext dbContext;
      
        public ProductServices(ProductDbContext dbContext)
        {
            this.dbContext = dbContext;
        }
      
        /// <summary>
        /// This method returns the list of product
        /// </summary>
        /// <returns></returns>
        public async Task<List<Product>> GetProductAsync()
        {
            return await dbContext.Product.ToListAsync();
        }
        /// <summary>
        /// This method add a new product to the DbContext and saves it
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public async Task<Product> AddProductAsync(Product product)
        {
            try
            {
                dbContext.Product.Add(product);
                await dbContext.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw;
            }
            return product;
        }
        /// <summary>
        /// This method update and existing product and saves the changes
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public async Task<Product> UpdateProductAsync(Product product)
        {
            try
            {
                var productExist = dbContext.Product.FirstOrDefault(p => p.Id == product.Id);
                if (productExist != null)
                {
                    dbContext.Update(product);
                    await dbContext.SaveChangesAsync();
                }
            }
            catch (Exception)
            {
                throw;
            }
            return product;
        }
        /// <summary>
        /// This method removes and existing product from the DbContext and saves it
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public async Task DeleteProductAsync(Product product)
        {
            try
            {
                dbContext.Product.Remove(product);
                await dbContext.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw;
            }
        }
       
    }
    

    3.Add using statements in _Imports.razor (Your namespace)

    @using BlazorEfcSQ.Data
    

    4.Register the ProductDbContext and ProductService in the ConfigureServices() method of Startup.cs,or in the Program.cs (asp.net core 6+), below is in the Program.cs:

    builder.Services.AddDbContext<ProductDbContext>(options =>
    {
        options.UseSqlite("Data Source = ProductsDB.db");
    });
    builder.Services.AddScoped<ProductServices>();
    

    5.Add the user interface code and logic to index.razor file.

    @page "/"
    @inject ProductServices service
    <div class="container">
        <div class="row bg-light">
            <table class="table table-bordered">
                <thead class="thead-dark">
                    <tr>
                        <th>Product Id</th>
                        <th>Name</th>
                        
                        <th>Delete Product</th>
                    </tr>
                </thead>
                <tbody>
                    @if (Products.Any())
                    {
                        @foreach (var product in Products)
                        {
                            <tr @onclick="(() => SetProductForUpdate(product))">
                                <td>@product.Id</td>
                                <td>@product.Name</td>
                               
                                <td><button class="btn btn-danger" @onclick="(() => DeleteProduct(product))">Delete</button></td>
                            </tr>
                        }
                    }
                    else
                    {
                        <tr><td colspan="6"><strong>No products available</strong></td></tr>
                    }
                </tbody>
            </table>
        </div>
        <div class="row m-5">
            <div class="col-5 bg-light m-2 justify-content-start">
                <div class="p-3 mb-3 bg-primary text-white text-center">Add New Product</div>
                <EditForm Model="@NewProduct">
                    <div class="form-group">
                        <label for="name">Product Name</label>
                        <input type="text" id="name" class="form-control" @bind-value="@NewProduct.Name" />
                    </div>
                   
                    <div class="text-center p-3 mb-3">
                        <button class="btn btn-info" @onclick="AddNewProduct"> Add Product</button>
                    </div>
                </EditForm>
            </div>
            <div class="col-5 bg-light m-2 justify-content-end">
                <div class="p-3 mb-1 bg-primary text-white text-center">Update Product</div>
                <EditForm Model="@UpdateProduct">
                    <div class="form-group">
                        <label for="name">Product Name</label>
                        <input type="text" id="name" class="form-control" @bind-value="@UpdateProduct.Name" />
                    </div>
                    
                    <div class="text-center p-3 mb-3">
                        <button class="btn btn-info" @onclick="UpdateProductData"> Update Product</button>
                    </div>
                </EditForm>
            </div>
        </div>
    </div>
    @code {
        List<Product> Products = new List<Product>();
        protected override async Task OnInitializedAsync()
        {
            await RefreshProducts();
        }
        private async Task RefreshProducts()
        {
            Products = await service.GetProductAsync();
        }
        public Product NewProduct { get; set; } = new Product();
        private async Task AddNewProduct()
        {
            await service.AddProductAsync(NewProduct);
            NewProduct = new Product();
            await RefreshProducts();
        }
        Product UpdateProduct = new Product();
        private void SetProductForUpdate(Product product)
        {
            UpdateProduct = product;
        }
        private async Task UpdateProductData()
        {
            await service.UpdateProductAsync(UpdateProduct);
            await RefreshProducts();
        }
        private async Task DeleteProduct(Product product)
        {
            await service.DeleteProductAsync(product);
            await RefreshProducts();
        }
    }
    

    6.Add CSS snippet into the site.css file: This will update the background of the table row whenever the mouse hovers over it.

     tr:hover {
            background-color:lightgray;
        }
    

    7.Add-Migration and Update-Database:

    Open the Package Manager Console and execute the following two commands.

    1. Add-Migration “Initial-Commit”
      • This command will create a migration folder into the project hierarchy and add a C# class file containing the migration details.

    Update-Database

    • This command will apply the “Initial-Commit” migration and create the database in the projects folder.

    Result:

    SQLITE

    Besides, you can read ASP.NET Core Blazor Server with Entity Framework Core (EF Core) to know more.

    Best regards,
    Qing Guo


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.