首页 > 解决方案 > 如何在实体框架中拦截和更改插入语句

问题描述

最近我不得不向现有的数据仓库添加一个新的数据源。这个数据源有一些表字段超过了我在数据仓库中的当前字段大小。由于非技术原因,我不应该更改 Datawarehouse 的 Fieldsize。

我想要做的是使用实体框架的拦截系统来检查插入和修剪字段到定义的长度(在属性中可用,代码优先方法)

到目前为止我得到了什么:

public class StringTrimmerInterceptor : IDbCommandTreeInterceptor
{
    void IDbCommandTreeInterceptor.TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
    {
        if (interceptionContext.OriginalResult.DataSpace != DataSpace.SSpace)
            return;

        var insertCommand = interceptionContext.Result as DbInsertCommandTree;
        if (insertCommand != null)
        {
            //Check and Trim oversized Fields

        }

    }
}

上面的代码可以找到我想要更改的正确插入语句。我想知道的是如何实际更改和执行它们。

我确实找到了一些关于如何更改查询的示例,但没有真正更改插入/更新。

结果应该是这样的:如果我尝试使用名称保存客户:“MyCustomerWithanUnreasonableLongName”,我只想保存模型中指定的字符数,例如“MyCustomerWitha”

标签: c#entity-framework

解决方案


推荐阅读