// dotnet command reference https://docs.microsoft.com/en-us/ef/core/cli/dotnet // change to project folder that contains .csproj file, not sln file's folder, output files will be present in models folder dotnet ef dbcontext scaffold "Server=192.168.0.129;User=root;Password=lanbe123;Database=monitor" "Pomelo.EntityFrameworkCore.MySql" -o ./models
// 在生成的文件夹里面找到 monitorContext.cs 里面有生成的工具类
// Startup.cs public void ConfigureServices(IServiceCollection services) { // Replace with your connection string.
services.AddDbContext<monitorContext>( dbContextOptions => dbContextOptions .UseMySql(Configuration["ConnectionStrings:ConnMySql"], new MySqlServerVersion(new Version(5, 7, 19))) // The following three options help with debugging, but should // be changed or removed for production. .LogTo(Console.WriteLine, LogLevel.Information) .EnableSensitiveDataLogging() .EnableDetailedErrors() );
services.AddControllers(); }
EF query
Entity framework supports three types of queries: 1) LINQ-to-Entities, 2) Entity SQL, and 3) Native SQL
Entity SQL
Entity SQL is another way to create a query. It is processed by the Entity Framework’s Object Services directly. It returns ObjectQuery instead of IQueryable. You need an ObjectContext to create a query using Entity SQL. The following code snippet shows the same query result as the LINQ query above.
//Querying with Object Services and Entity SQL string sqlString = "SELECT VALUE st FROM SchoolDBEntities.Students " + "AS st WHERE st.StudentName == 'Bill'"; var objctx = (ctx as IObjectContextAdapter).ObjectContext; ObjectQuery<Student> student = objctx.CreateQuery<Student>(sqlString); Student newStudent = student.First<Student>();
Native SQL
using (var ctx = new SchoolDBEntities()) { var studentName = ctx.Students.SqlQuery("Select studentid, studentname, standardId from Student where studentname='Bill'").FirstOrDefault<Student>(); }
delete
var us = db.user.FirstOrDefault(x => x.uid == uid);