Common/sqlhelper.cs
(完整代码) 1KBusing System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Data.Entity.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
namespace WebApplication1.Common
{
public static class sqlhelper
{
/// <summary>
/// 修改指定属性的单条数据
/// </summary>
/// <typeparam name="T">实体</typeparam>
/// <param name="context">上下文</param>
/// <param name="model">要修改的实体信息</param>
/// <param name="expression">指定修改的字段</param>
public static void Modify<T>(this DbContext context, T model, Expression<Func<T, object>> expression)
where T : class
{
context.Update(model);
//4.1将 对象 添加到 EF中
var entry = context.Entry<T>(model);
//4.2先设置 对象的包装 状态为 Unchanged
entry.State = EntityState.Unchanged;
//4.3循环 被修改的属性名 数组
foreach (var proInfo in expression.GetPropertyAccessList())
{
if (!string.IsNullOrEmpty(proInfo.Name))
//4.4将每个 被修改的属性的状态 设置为已修改状态;后面生成update语句时,就只为已修改的属性 更新
entry.Property(proInfo.Name).IsModified = true;
}
}
}
}
24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明
AI 解读 AI
登录后可用,每次 10 积分,解读结果公开显示在下面。
还没有人解读过这个文件。
