using (var context = new MyDbContext()){ var newEntity = new Entity(); context.Add(newEntity); context.SaveCha">

c#怎么实现数据库的增删改查

来源:这里教程网 时间:2026-02-21 16:48:19 作者:

使用 C# 实现数据库的增删改查

使用

Entity Framework
提供的
DbContext.Add()
方法将新实体添加到数据库。

<code class="c#">using (var context = new MyDbContext())
{
  var newEntity = new Entity();
  context.Add(newEntity);
  context.SaveChanges();
}</code>

使用

Entity Framework
提供的
DbContext.Remove()
方法从数据库中删除现有实体。

<code class="c#">using (var context = new MyDbContext())
{
  var entityToBeDeleted = context.Entities.Find(entityId);
  context.Remove(entityToBeDeleted);
  context.SaveChanges();
}</code>

使用

Entity Framework
提供的
DbContext.Modify()
方法更新数据库中的现有实体。

<code class="c#">using (var context = new MyDbContext())
{
  var entityToBeUpdated = context.Entities.Find(entityId);
  // 修改实体属性
  entityToBeUpdated.Name = "Updated Name";
  context.SaveChanges();
}</code>

使用

Entity Framework
提供的
DbContext.Find()
DbContext.Query()
方法从数据库中检索实体。

<code class="c#">using (var context = new MyDbContext())
{
  // 根据主键查找实体
  var entity = context.Entities.Find(entityId);
  // 查询实体集合
  var entities = context.Entities.Query().ToList();
}</code>

相关推荐