EF代码优先:手动增加非自动增量字段

时间:2012-06-05 11:54:51

标签: entity-framework entity-framework-4 ef-code-first

我正在使用ERP中的现有数据库。

在我的所有数据库表中,都有一个名为“r_e_c_n_o_”的浮点字段,但该字段不会被数据库自动递增,我无法更改它。

对于所有添加的实体,我想增加这个字段“r_e_c_n_o_”,我怎么能在DbContext的SaveChanges()方法中实现呢?

使用ADO.NET我会做类似的事情:

    public static int GetNext(string tableName, string fieldName)
    {
        var cmd = _conn.CreateCommand(string.Format("SELECT MAX({0}) + 1 FROM {1}", fieldName, tableName));
        var result = (int)cmd.ExecuteScalar();
        return result;
    }

更新: 请看下面的评论,它正是我解决问题所需要的:

    public override int SaveChanges()
    {
        var entries = this.ChangeTracker.Entries();
        Dictionary<string, int> lastRecnos = new Dictionary<string, int>();
        foreach (var entry in entries)
        {
            var typeName = entry.Entity.GetType().Name;

            if (lastRecnos.ContainsKey(typeName))
                lastRecnos[typeName]++;
            else
                lastRecnos[typeName] = 0;//How can i get the max here?

            int nextRecnoForThisEntity = lastRecnos[typeName];

            var entity = entry.Entity as EntityBase;
            entity.Recno = nextRecnoForThisEntity;


        }
        return base.SaveChanges();
    }

韩国社交协会, 威廉

0 个答案:

没有答案