entity framework core 调用存储过程和方法

  目前EF Core调用存储过程,限制很多,比如返回结果必须是定义好的DbSet<>等等。这里用一种曲线救国的方式,自定义两个方法,用原始ado.net解决问题。以MySql数据库为例,代码如下:

 namespace WebApi.Core.Data
{
using System.Data;
using System.Linq; using Microsoft.EntityFrameworkCore; using MySql.Data.MySqlClient; public class TestContext : DbContext
{
public TestContext(DbContextOptions<TestContext> options)
: base(options)
{
} public int ExcuteProcedure(string parcedureName, params MySqlParameter[] ps)
{
using (var cmd = this.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = parcedureName;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(ps);
this.Database.OpenConnection();
var r = cmd.ExecuteNonQuery();
this.Database.CloseConnection();
return r;
}
} public object ExcuteFunction(string functionName, params MySqlParameter[] ps)
{
using (var cmd = this.Database.GetDbConnection().CreateCommand())
{
// 参数字符串,传参时注意顺序
var pString =
$"'{ps.Aggregate(string.Empty, (c, n) => $"{c}','{n.Value}").TrimStart(new[] { ',', '\'' })}'"; // 可用this.Database.IsXXX(),判读数据库类型,拼command字符串,这里不写了
cmd.CommandText = $"select {functionName}({pString});";
this.Database.OpenConnection();
var r = cmd.ExecuteScalar();
this.Database.CloseConnection();
return r;
}
} protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
}
}
上一篇:PHP7安装笔记


下一篇:VR制作的规格分析