使用 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> 