ServiceStack ORMLite Cannot Update Identity Column

余生长醉 提交于 2020-01-05 05:47:12

问题


I am using ServiceStack ORMLite to try and update a record in my database. All of my POCO's implement an IHasID interface

public interface IHasId
{
    int Id { get; set; }
}

In my POCO I have the following property

private int id;

[ServiceStack.DataAnnotations.Alias("TableName_ID")]
    public int Id
    {
        get { return id; }
        set
        {
            if (value != this.id)
            {
                this.id = value;                    
                NotifyPropertyChanged("Id");
            }
        }
    }

Each of my repository classes inherits a from a DataRepositoryBase< T> class that has the following method:

public virtual T Update(T entity)
    {
        using (IDbConnection db = CreateDbConnection())
        {
            db.Update<T>(entity, e => e.Id == entity.Id);
            return entity;
        }
    }

When I call this method on the child repository I get the following error:

System.Data.SqlClient.SqlException (0x80131904): Cannot update identity column 'TableName_ID'.

How can I fix this error?

What am I doing wrong?

Thanks!

Jeremy


回答1:


You should also label Identity columns with [AutoIncrement], e.g:

[AutoIncrement]
[Alias("TableName_ID")]
public int Id { ... ]



回答2:


You don't usually update identity fields as they are generated automatically by the database. There are specific cases where you might want to update an identity field but you need to do this with SQL as it requires you to use a SET statement at the begining an end of each query.



来源:https://stackoverflow.com/questions/19277431/servicestack-ormlite-cannot-update-identity-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!