重写OnConfiguring方法,配置数据库连接
。protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(" Data Source = 127.0.0.1; Initial Catalog = demo2; User ID = *; Password = ***");
}
在appsettings.Json中添加
。{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"connstring": optionsBuilder.UseSqlServer(" Data Source = 127.0.0.1; Initial Catalog = demo2; User ID = *; Password = ***");
}
}
//在ConfigureServices方法中写入
services.AddControllers();
services.AddCors(option => option.AddPolicy("cors", c => c.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
//我的上下文对象名为:MyContext
services.AddDbContext<MyContext>();
//在Configure方法中写入
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();//路由
app.UseAuthorization();//身份认证
app.UseCors("cors");//跨域
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
到这里webapi+ef core就能使用了。但是只能使用具体类的lambda表达式和具体类的执行SQL语句。
但在EF Core(EF Core版本为3.1.3)提供的的执行SQL语句的方法发现许多问题,比如:
不支持返回特定的泛型类型的元素(通过映射出来的泛型类)。
执行SQL查询语句查询某张表时查询返回的字段必须是该表的所有字段。
public static class EntityFrameworkCoreExtensions
{
private static DbCommand CreateCommand(DatabaseFacade facade, string sql, out DbConnection connection, params object[] parameters)
{
var conn = facade.GetDbConnection();
connection = conn;
conn.Open();
var cmd = conn.CreateCommand();
if (facade.IsSqlServer())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
}
return cmd;
}
public static DataTable SqlQuery(this DatabaseFacade facade, string sql, params object[] parameters)
{
var command = CreateCommand(facade, sql, out DbConnection conn, parameters);
var reader = command.ExecuteReader();
var dt = new DataTable();
dt.Load(reader);
reader.Close();
conn.Close();
return dt;
}
public static List<T> SqlQuery<T>(this DatabaseFacade facade, string sql, params object[] parameters) where T : class, new()
{
var dt = SqlQuery(facade, sql, parameters);
return dt.ToList<T>();
}
public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
var propertyInfos = typeof(T).GetProperties();
var list = new List<T>();
foreach (DataRow row in dt.Rows)
{
var t = new T();
foreach (PropertyInfo p in propertyInfos)
{
if (dt.Columns.IndexOf(p.Name) != -1 && row[p.Name] != DBNull.Value)
p.SetValue(t, row[p.Name], null);
}
list.Add(t);
}
return list;
}
}
具体使用示例:
using (MyContext db = new MyContext())
{
var datas=db.Database.SqlQuery<T>("select * from tabname").FirstOrDefault();
}
注:【model类设置主键自增:[Key] //主键
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] //设置自增】