.netCore ABP 只修改部分字段 只更新部分列
using Abp.Dependency;
using Abp.EntityFrameworkCore;
using AutoCodePlan.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AutoCodePlan.Sql
{
/// <summary>
/// 指定更新部分字段
/// </summary>
public interface ICustomModity
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="fields"></param>
/// <returns></returns>
int UpdateEntityFields<T>(T entity, IList<string> fields) where T : class, new();
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="fields"></param>
/// <returns></returns>
Task<int> UpdateEntityFieldsAsync<T>(T entity, IList<string> fields) where T : class, new();
}
/// <summary>
///
/// </summary>
public class CustomModity : ICustomModity, ITransientDependency
{
private IDbContextProvider<AutoCodePlanDbContext> _dbContextProvider = null;
/// <summary>
///
/// </summary>
/// <param name="dbContextProvider"></param>
public CustomModity(IDbContextProvider<AutoCodePlanDbContext> dbContextProvider)
{
_dbContextProvider = dbContextProvider;//IocManager.Instance.Resolve<IDbContextProvider<OADbContext>>();
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="fields"></param>
/// <returns></returns>
public int UpdateEntityFields<T>(T entity, IList<string> fields) where T : class, new()
{
if (entity == null || fields == null || fields.Count == 0)
{
return 0;
}
//db.Set<T>().Attach(entity);
var db = _dbContextProvider.GetDbContext();
db.Set<T>().Attach(entity);
foreach (var item in fields)
{
db.Entry(entity).Property(item).IsModified = true;
}
return db.SaveChanges();
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="fields"></param>
/// <returns></returns>
public async Task<int> UpdateEntityFieldsAsync<T>(T entity, IList<string> fields) where T : class, new()
{
if (entity == null || fields == null || fields.Count == 0)
{
return 0;
}
//db.Set<T>().Attach(entity);
var db = _dbContextProvider.GetDbContext();
db.Set<T>().Attach(entity);
foreach (var item in fields)
{
db.Entry(entity).Property(item).IsModified = true;
}
return await db.SaveChangesAsync();
}
}
}