Blazor Server 是一个 Web 应用程序开发框架,使用 EF Core 进行数据库连接和数据访问。下面是一些示例代码,用于演示在 Blazor Server 中使用 EF Core 进行数据库连接和查询操作。
在项目中添加 Microsoft.EntityFrameworkCore 和 Microsoft.EntityFrameworkCore.SqlServer NuGet 包。
在项目中创建 DbContext 的子类,用于定义应用程序所需的实体和数据库表之间的映射关系。以下是一个简单的示例:
using Microsoft.EntityFrameworkCore;
namespace BlazorApp.Server.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public DbSet Students { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity().ToTable("Student");
}
}
}
在 Startup.cs 文件中的 ConfigureServices 方法中注册 DbContext:
services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("AppDbContext")));
在项目中创建一个 Repository 类,用于实现对数据库的操作。以下是一个简单的示例:
using System.Collections.Generic;
using System.Linq;
using BlazorApp.Shared;
using Microsoft.EntityFrameworkCore;
namespace BlazorApp.Server.Data
{
public class StudentRepository
{
private readonly AppDbContext _context;
public StudentRepository(AppDbContext context)
{
_context = context;
}
public List GetStudents()
{
return _context.Students.ToList();
}
public void AddStudent(Student student)
{
_context.Students.Add(student);
_context.SaveChanges();
}
public void UpdateStudent(Student student)
{
_context.Students.Attach(student);
_context.Entry(student).State = EntityState.Modified;
_context.SaveChanges();
}
public void DeleteStudent(int id)
{
var student = _context.Students.Find(id);
if (student != null)
{
_context.Students.Remove(student
上一篇:BlazorSelectElementICanNotSetTheChangeEvent
下一篇:BlazorServer,ZXingbarcodescanner-ThecurrentthreadisnotassociatedwiththeDispatcher.Howtocorrect?