Skip to content

[TOC]

实体类配置

单个实体类配置

C
using Microsoft.EntityFrameworkCore;
using WebApplication1.Entity;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace WebAppliction1.Entity.Configuration
{
    public class UserConfiguration : IEntityTypeConfiguration<User>
    {
        public void Configure(EntityTypeBuilder<User> modelBuilder)
        {
            modelBuilder.ToTable("User");
            modelBuilder.Property(e => e.Id).IsRequired(); 
        }
    }
}

然后在继承 : DbContext 的 protected override void OnModelCreating(ModelBuilder modelBuilder) 方法上 添加如下代码:


using Microsoft.EntityFrameworkCore; 
    public class DatabaseContext : DbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {  
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
        }
    }

创建主键

C
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<YourEntity>()
        .HasKey(e => e.YourProperty); // 单属性主键
}

创建唯一键

注意 HasIndex

C
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<YourEntity>()
        .HasIndex(e => e.YourProperty).IsUnique(); // 单属性主键
}

TestDbContext 类

using Microsoft.EntityFrameworkCore;
using WebApplication2.Class.Entity;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

namespace WebApplication2.Comment.DataBaseConfig
{
    public class DatabaseContext : DbContext
    {  
        public DatabaseContext(DbContextOptions<DatabaseContext> options)
            : base(options)
        {
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {  
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var loggerFactory = LoggerFactory.Create(builder =>
                builder.AddConsole());
        }
    }
}

更改数据函数

C
_context.Set<实体类>().
await _context.SaveChangesAsync();

Program

C

            IServiceCollection services = builder.Services;
            #region Database

            // ? 2. 自动获取连接字符串
            var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new InvalidOperationException(
                    "Database connection string 'DefaultConnection' not found in dbsettings.json"
                );
            }
            // ? 4. 自动注册数据库(核心!)
            services.AddDbContext<DatabaseContext>(options =>
            {
                options.UseSqlServer(connectionString);
            });

Ef CORE left join 连接

C

        builder.HasMany(p => p.Roles)
            .WithMany(r => r.Permissions)
             .UsingEntity<Role_L_Permission>(
                  j => j.HasOne(r => r.TheRole) // 这里要改成 typeof(Permission)
                       .WithMany()
                       .HasForeignKey("RoleId"),
                    // 中间表名
                    j => j.HasOne(a => a.ThePermission) // 这里要改成 typeof(Role)
                       .WithMany()
                       .HasForeignKey("PermissionId")
                       ,
                  ent =>
                  {
                      // 因为这两个是影子属性,必须显式配置
                      // 否则找不到属性,会报错
                      ent.Property<long>("PermissionId");
                      ent.Property<long>("RoleId");
                      // 两个属性都是主键
                      ent.HasKey("PermissionId", "RoleId");
                  } 
             );

迁移命令

Add-Migration InitialCreate  成功后生成文件

Update-database

事务

using (var transaction = await _dbContext.Database.BeginTransactionAsync())
{
    try
    {
        
// 在控制器中
await _Service.AddOK(transaction);
        // 异步操作
        await _dbContext.YourEntities.AddAsync(newEntity);
        await _dbContext.SaveChangesAsync();
        
        await transaction.CommitAsync();
    }
    catch
    {
        await transaction.RollbackAsync();
        throw;
    }
}



// 在Service中添加一个接受事务的方法
public async Task AddOK(IDbContextTransaction transaction)
{
    // 使用传入的事务
    _dbContext.Database.UseTransaction(transaction.GetDbTransaction());
    // ...其他操作
}

关系配置

C
public class