0

在我的代码中的几个地方,我正在使用方便的花花公子Z.EntityFramework.Plus扩展进行批量更新,例如

await db.Foos
        .Where(f => f.SomeCondition)
        .UpdateAsync(f => new Foo { Field1 = "bar", Field2 = f.Field2 + 1 });

这将更新所有Foo记录SomeCondition为真,设置Field1为“栏”,Field2并将增加一。

现在出现了一个新要求,其中一些表(但不是全部)正在跟踪ModifiedDate。这包括我正在进行批量更新的记录。

所以我的方法是这样的。我有一个界面:

public interface ITrackModifiedDate
{
    DateTime ModifiedDate { get; set; }
}

所以我所有的跟踪类都ModifiedDate可以实现ITrackModifiedDate。然后,我编写了一个中间人扩展来拦截.UpdateAsync()调用:

public static async Task<int> UpdateAsync<T>(this IQueryable<T> queryable, Expression<Func<T, T>> updateFactory)
        where T : class
{
    if (typeof(ITrackModifiedDate).IsAssignableFrom(typeof(T)))
    {
        // TODO Now what?
    }

    return await BatchUpdateExtensions.UpdateAsync(queryable, updateFactory);
}

如您所见,除了已经更新的任何其他字段之外,我不完全确定如何修改为updateFactoryset 。ModifiedDateDateTime.UtcNow

怎么做?

更新:我不反对更改我的扩展名,以便它只接受Ttype ITrackModifiedDate,如果有帮助的话,即

public static async Task<int> UpdateAsync<T>(this IQueryable<T> queryable, Expression<Func<T, T>> updateFactory)
    where T : class, ITrackModifiedDate
{
        // TODO what now?

    return await BatchUpdateExtensions.UpdateAsync(queryable, updateFactory);
}
4

1 回答 1

1

我让它使用以下代码:

using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Z.EntityFramework.Plus; 

class Program
{
    static async Task Main(string[] args)
    {
        using (var context = new SomeContext())
        {
            await context
                .Customers
                .Where(c => c.Email.Contains("42"))
                .CustomUpdateAsync((c) => new Customer()
                {
                    Email = "4242"
                });
        }
    }

}

public static class Helper
{
    public static async Task<int> CustomUpdateAsync<T>(this IQueryable<T> queryable, Expression<Func<T, T>> updateFactory)
        where T : class
    {
        var targetType = typeof(T);
        if (typeof(ITrackModifiedDate).IsAssignableFrom(targetType))
        {
            updateFactory = (Expression<Func<T, T>>)new TrackModifiedDateVisitor().Modify(updateFactory);
        }

        return await BatchUpdateExtensions.UpdateAsync(queryable, updateFactory);
    }
}


public class TrackModifiedDateVisitor : ExpressionVisitor
{
    public Expression Modify(Expression expression)
    {
        return Visit(expression);
    }

    public override Expression Visit(Expression node)
    {
        if (node is MemberInitExpression initExpression)
        {
            var existingBindings = initExpression.Bindings.ToList();
            var modifiedProperty = initExpression.NewExpression.Type.GetProperty(nameof(ITrackModifiedDate.ModifiedDate));

            // it will be `some.ModifiedDate = currentDate`
            var modifiedExpression = Expression.Bind(
                modifiedProperty,
                Expression.Constant(DateTime.Now, typeof(DateTime))
                );

            existingBindings.Add(modifiedExpression);

            // and then we just generate new MemberInit expression but with additional property assigment
            return base.Visit(Expression.MemberInit(initExpression.NewExpression, existingBindings));
        }

        return base.Visit(node);
    }
}


public class SomeContext: DbContext
{
    public SomeContext()
        : base("Data Source=.;Initial Catalog=TestDb;Integrated Security=SSPI;")
    {
        Database.SetInitializer(new CreateDatabaseIfNotExists<SomeContext>());
    }

    public DbSet<Customer> Customers { get; set; }
}

public class Customer: ITrackModifiedDate
{
    public int ID { get; set; }
    public string Email { get; set; }
    public DateTime ModifiedDate { get; set; }
}

public interface ITrackModifiedDate
{
    DateTime ModifiedDate { get; set; }
}

需要的部分是TrackModifiedDateVisitor遍历updateFactory表达式以及何时找到MemberInitExpression并更新它的类。最初它有一个属性分配列表,我们为现有分配生成一个ModifiedDate新的并MemberInitExpression使用现有分配加上生成的一个。

作为访问者代码执行后的结果 -updateFactory会有

c => new Customer() {Email = "4242", ModifiedDate = 5/16/2019 23:19:00}
于 2019-05-16T20:20:28.397 回答