简介
Entity Framework Core (EF Core)是微软推荐的基于.NET Core 的应用程序数据访问技术。开源,轻量级,可扩展并且支持跨平台开发。EF Core是一种对象关系映射器(ORM),通过应用程序实体对象和关系数据库中的数据的映射,使得开发人员能够以面向对象的方式处理数据。
使用
在项目里头安装EF Core和MySQL相关的NuGet包:Microsoft.EntityFrameworkCore,Pomelo.EntityFrameworkCore.MySql ,如果你使用的是其他数据库,那么就换成其他的数据库相关的包即可。
这里创建的是一个web项目,桌面项目其实大同小异,创建一个类继承DbContext,DbContext 是 EF 中非常重要的一个组件,它拥有数据库的会话连接,数据查询,修改保存数据,缓存,事务管理等等作用。
比如我这里创建的是这样的:
usingAcg.Models; usingMicrosoft.EntityFrameworkCore; namespaceAcg.DataBase{ publicclassAcgbiuDbContext : DbContext { publicDbSet<TopicModel>Acgbiu_Topic { get; set; } publicDbSet<TopicRelationshipsModel>Acgbiu_Topic_Relationships { get; set; } publicDbSet<TermModel>Acgbiu_Terms { get; set; } publicDbSet<FocusModel>Acgbiu_Focus { get; set; } publicAcgbiuDbContext(DbContextOptions<AcgbiuDbContext>options) : base(options) { this.Database.Migrate(); } protectedoverridevoidOnModelCreating(ModelBuildermodelBuilder) { modelBuilder.Entity<TopicModel>(); modelBuilder.Entity<TopicRelationshipsModel>(); modelBuilder.Entity<FocusModel>(); } } }
创建实体类,对应数据库中的表结构,比如我这里的TopicModel。
usingSystem.ComponentModel.DataAnnotations; usingSystem.ComponentModel.DataAnnotations.Schema; namespaceAcg.Models{ [Table("acgbiu_topic")] publicclassTopicModel { [Key] publicinttopic_id { get; set; } publicstringname { get; set; } publicstringdescription { get; set; } publicstringicon { get; set; } publicstringremark { get; set; } } }
使用依赖注入的方式使用刚才创建的AcgbiuDbContext ,在Startup.cs中注册AcgbiuDbContext。
publicvoidConfigureServices(IServiceCollectionservices) { services.AddControllersWithViews(); stringconnectStr=$"server = 服务器地址; port=端口号;database = 使用的数据库; uid = 数据库连接用户名; password = 密码"; services.AddDbContext<AcgbiuDbContext>(oprions=>oprions.UseMySql(connectStr, newMySqlServerVersion(newVersion(10,5,6)))); }
以一个控制器类的代码为例,看下数据的增删改查。
构造函数注入的方式,获取我们刚才注册的AcgbiuDbContext,然后就可以使用了。
//获取表的所有数据AcgbiuDbContext.Acgbiu_Topic.ToList(); //添加数据AcgbiuDbContext.Acgbiu_Topic.Add(topicModel); //更新数据AcgbiuDbContext.Acgbiu_Topic.Update(topicModel); //删除数据AcgbiuDbContext.Acgbiu_Topic.Remove(topic); //异步的方式将前面的增删改,保存到数据库中awaitAcgbiuDbContext.SaveChangesAsync();
usingAcg.DataBase; usingAcg.Models; usingMicrosoft.AspNetCore.Mvc; usingMicrosoft.Extensions.Configuration; usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Threading.Tasks; namespaceAcg.Controllers{ [Route("Api/[controller]/[action]/{id?}")] publicclassApiTopicController: ControllerBase { privatereadonlyIConfigurationConfiguration; privatereadonlyAcgbiuDbContextAcgbiuDbContext; publicApiTopicController(IConfigurationconfiguration, AcgbiuDbContextacgbiuDbContext) { Configuration=configuration; AcgbiuDbContext=acgbiuDbContext; } [HttpGet] publicasyncTask<IActionResult>Topics(intid) { List<TopicModel>topicModels=newList<TopicModel>(); topicModels=AcgbiuDbContext.Acgbiu_Topic.ToList(); if (id!=0) { TopicModeltopicModel=topicModels.Find(x=>x.topic_id==id); returnnewJsonResult(topicModel); } returnnewJsonResult(topicModels); } [HttpPost] publicasyncTask<IActionResult>Topics([FromBody] TopicModeltopicModel) { boolres=true; AcgbiuDbContext.Acgbiu_Topic.Add(topicModel); intnum=awaitAcgbiuDbContext.SaveChangesAsync(); if (num<=0) { res=false; } returnnewJsonResult(num); } [HttpPut] publicasyncTask<IActionResult>Topics(intid,[FromBody]TopicModeltopicModel) { boolres=true; if (id!=topicModel.topic_id) { returnBadRequest(); } AcgbiuDbContext.Acgbiu_Topic.Update(topicModel); intnum=awaitAcgbiuDbContext.SaveChangesAsync(); returnnewJsonResult(num); } [HttpDelete] publicasyncTask<IActionResult>Topics(longid) { vartopic=awaitAcgbiuDbContext.Acgbiu_Topic.FindAsync(id); if (topic==null) { returnNotFound(); } AcgbiuDbContext.Acgbiu_Topic.Remove(topic); awaitAcgbiuDbContext.SaveChangesAsync(); returnNoContent(); } [HttpGet] publicasyncTask<IActionResult>TopicTerms(intid) { if (id>0) { varterms=AcgbiuDbContext.Acgbiu_Topic_Relationships.Join(AcgbiuDbContext.Acgbiu_Terms, x=>x.term_id, y=>y.term_id, (x, y) =>new { x.id, x.topic_id, x.term_id, y.name, y.slug }).Where(p=>p.topic_id==id).ToList(); returnnewJsonResult(terms); } else { varterms=AcgbiuDbContext.Acgbiu_Topic_Relationships.Join(AcgbiuDbContext.Acgbiu_Terms, x=>x.term_id, y=>y.term_id, (x, y) =>new { x.id, x.topic_id, x.term_id, y.name, y.slug }).ToList(); returnnewJsonResult(terms); } } [HttpPost] publicasyncTask<IActionResult>TopicTerms([FromBody] TopicRelationshipsModeltopicRelationshipsModel) { try { if (topicRelationshipsModel==null||topicRelationshipsModel.topic_id==0||topicRelationshipsModel.term_id==0) { returnBadRequest(); } boolisExist=AcgbiuDbContext.Acgbiu_Topic_Relationships.Any(x=>x.topic_id==topicRelationshipsModel.topic_id&&x.term_id==topicRelationshipsModel.term_id); if (!isExist) { awaitAcgbiuDbContext.Acgbiu_Topic_Relationships.AddAsync(topicRelationshipsModel); awaitAcgbiuDbContext.SaveChangesAsync(); } else { returnBadRequest(); } }catch(Exceptionex) { returnBadRequest(); } returnNoContent(); } } }