Massive:更新对象:无法更新标识列

时间:2012-11-16 21:52:56

标签: c# dynamic massive

我有以下情景......

  • Massive Micro-ORM
  • .NET framework 4.0
  • SQL Server 2008R2

型号:

public class sUser : DynamicModel
{
    public sUser() : base(Model.strConnection, "Users", "UserId") { }
}

public class Test
    {
        public void UpdateUser(string user)
        {
            dynamic User = GetUser(user);

            //Dynamically generated User object has many columns
            // I Update following fields...
            User.Address1 = "123 Main Street";
            User.Address2 = "Suite# 456";
            User.CityName = "Princeton";
            User.State = "NJ";
            User.Zipcode = "08540";
            //And update some more fields in Users object

           //I could do this...
            //var upd = new { Address1 = "123 Main Street", Address2 = "Suite# 456", ...};
            //User.Update(upd, User.UserID);

            //But would like to pass entire object, so I do not have to form all updated name/value in the update statement
            User.Update(User, User.UserID);

            //But Users table has a column with IDENTITY SEED,
            //And if I pass entire object for update it errors out
            //Cannot update identity column 'RefNo'
        }

        public dynamic GetUser(string userName)
        { 
            dynamic table = new sUser();
            var objUser = table.First(UserName: userName);

            return objUser;
        }
    }

Users表有一个RefNo列IDENTITY SEED=1,当我更新整个User对象时,它出错了无法更新标识列'RefNo'。我想传递整个对象进行更新,而不是形成长更新语句。

我该如何处理?

感谢。

2 个答案:

答案 0 :(得分:1)

如果您的“用户”表格中包含RefNoIDENTITY SEED = 1,那么这意味着它是您的主键。在您sUser类中,您使用以下命令调用基础构造函数:

base(Model.strConnection, "Users", "UserId")

此调用告诉Massive主键列为UserId - 如果您将其传递给RefNo会怎样?

修改

我想我看到了你遇到的问题:Massive会生成一个更新语句,其中包括对象的所有属性,包括RefNo。由于数据库正在处理此列(通过IDENTITY SEED),因此您无法修改或设置此值。

我建议改为利用User作为ExpandoObject返回的事实。你能做的是:

((IDictionary<string, object>)User).Remove("RefNo");
User.Update(User, User.UserID);

这样做是从对象中删除RefNo属性,这意味着它不会包含在创建的更新语句中,这反过来会导致Update调用成功

答案 1 :(得分:0)

修改Massive.cs - 在 DynamicModel

下添加以下内容
private string IdentityColumn { get; set; }

 private string GetIdentityColumn()
 {
    return (string)Scalar("SELECT C.name AS IdentityColumn FROM sys.columns C Inner Join sys.tables T ON T.object_id = C.object_id WHERE C.is_identity = 1 And T.name = '" + TableName + "'");
 }

CreateUpdateCommand 方法下添加以下内容......

IdentityColumn = GetIdentityColumn();

foreach 循环下,将 if statement 修改为以下内容...

if (!item.Key.Equals(PrimaryKeyField, StringComparison.OrdinalIgnoreCase) && item.Value != null && item.Key != IdentityColumn)

以上对Massive库的更改将允许我们使用标识列更新模型。限制:适用于具有一个IDENTITY列的表。