使用EntityFrameworkCore
虽然Nebula默认使用ClownFish中提供的数据访问模块,但也支持使用其它的数据访问模块。
本文将介绍如何在Nebula中使用EntityFrameworkCore
添加NuGet包
例如:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.2" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.0" />
定义EF-DbContext继承类
示例代码如下
public class MyNorthwindEfDbContext : Microsoft.EntityFrameworkCore.DbContext
{
public DbSet<Product> Product { get; set; }
private readonly DbConfig _dbConfig;
public MyNorthwindEfDbContext(DbConfig dbConfig)
{
_dbConfig = dbConfig;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connectionString = _dbConfig.GetConnectionString(true);
if( _dbConfig.DbType == DatabaseType.SQLSERVER )
optionsBuilder.UseSqlServer(connectionString);
else if( _dbConfig.DbType == DatabaseType.MySQL ) {
ServerVersion version = ServerVersion.AutoDetect(connectionString);
optionsBuilder.UseMySql(connectionString, version, null);
}
else if( _dbConfig.DbType == DatabaseType.PostgreSQL )
optionsBuilder.UseNpgsql(connectionString);
else if( _dbConfig.DbType == DatabaseType.DaMeng )
optionsBuilder.UseDm(connectionString);
else
throw new NotSupportedException();
}
}
在代码中使用
以下代码来自 Controller 中的示例
[Route("search/{index}/{size}.aspx")]
public PageListResult<Product> Search([FromBody] ProductSearchParam product, int index, int size)
{
PageListResult<Product> result = new PageListResult<Product>();
result.PagingInfo = new PagingInfo();
result.PagingInfo.PageIndex = index;
result.PagingInfo.PageSize = size;
DbConfig dbConfig = DbConnManager.GetAppDbConfig("conn-name");
using( MyNorthwindEfDbContext dbContext = new MyNorthwindEfDbContext(dbConfig) ) {
var query = dbContext.Product.Select(x => x);
if( product.CategoryID > 0 )
query = query.Where(x => x.CategoryID == product.CategoryID);
if( product.UnitPrice > 0 )
query = query.Where(x => x.UnitPrice > product.UnitPrice);
if( product.Unit.HasValue() )
query = query.Where(x => x.Unit == product.Unit);
if( product.ProductName.HasValue() )
query = query.Where(x => EF.Functions.Like(x.ProductName, product.ProductName + "%"));
query = query.OrderBy(x => x.ProductID);
result.Data = query.ToList();
return result;
}
}
性能日志展示如下: