1.引入Nuget包:
2.书写EF操作上下文
public class MySqlContext:DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBulder)
{
optionsBulder.UseMySQL("Database=newspublish;Data Source=127.0.0.1;Port=3306;User Id=root;Password=123456;Charset=utf8;SslMode=none;");
}
public virtual DbSet news { get; set; }
}
news类:
public class news
{
public int id { get; set; }
public string title { get; set; }
public string content { get; set; }
public int typeid { get; set; }
}
3.操作mysql数据库
MySqlContext context = new MySqlContext();
#region 新增
context.news.Add(new news { title = "aaaa", content = "0000", typeid = 8 });
context.SaveChanges();
#endregion
#region 查询
Console.WriteLine(context.news.Find(12).title);
#endregion
#region 更新
var news = context.news.Find(12);
news.title = "sada";
news.content = "2121";
context.news.Update(news);
context.SaveChanges();
#endregion
#region 删除
context.news.Remove(new news { id = 12});
context.SaveChanges();
#endregion