error when saving Entity with ormlite

849 views
Skip to first unread message

Aaron Fischer

unread,
Feb 24, 2012, 7:10:20 PM2/24/12
to servic...@googlegroups.com
hello, when I try to update my files table in SQL server I am reviving this error message: "Cannot insert explicit value for identity column in table 'Files' when IDENTITY_INSERT is set to OFF." 
Any thoughts on what might be causing this?  below is a simple class and function of how I am working with ormlite.


public class Files
{
public string F100 { get; set; }
public string F101 { get; set; }
public string FileName { get; set; }
public int FileSize { get; set; }
public int IEventId { get; set; }
[ServiceStack.DataAnnotations.AutoIncrement]
public int? IFileId { get; set; }
public int IFolderId { get; set; }
public Files()
{

}
}

int SomeUpdate( int FileID )
{
using( var dbConn = Helpers.dbFactory().OpenDbConnection())
using( var dbCmd = dbConn.CreateCommand())
using ( var transaction = dbCmd.BeginTransaction())
{
dbCmd.CommandTimeout = Helpers.DatabaseCommandTimeOut;

tFiles.IFolderId = iFolderID;
tFiles.FileName = Microsoft.VisualBasic.Strings.Left(sLongName, 255);

if ( FileID > 0 )
{
tFiles.IFileId = FileID;
dbCmd.Save( tFiles );

tFiles = null;
}
else
{
dbCmd.Insert( tFiles );
FileID = ( int )dbCmd.GetLastInsertId(); //Get Auto Inserted Id;

tFiles = null;
}

transaction.Commit();

}
return FileID;
}

Demis Bellot

unread,
Feb 24, 2012, 7:18:59 PM2/24/12
to servic...@googlegroups.com
You need to specify an Id primary key. 
By default it should be the property on the POCO should be 'Id' (unless you can change it with ModelConfig()), You can then use an alias to map it to a different field:

public class Files
{
[ServiceStack.DataAnnotations.AutoIncrement]
[Alias("IFileId")]
public int? Id { get; set; }

public string F100 { get; set; }
public string F101 { get; set; }
public string FileName { get; set; }
public int FileSize { get; set; }
public int IEventId { get; set; }

kpfishon

unread,
Mar 14, 2014, 8:09:51 AM3/14/14
to servic...@googlegroups.com
Demis, you included the [AutoIncrement] annotation in your example, but not in your description.  Just so no one else misses this, if your table exists with an IDENTITY column on it just having the Id property is not enough it has to be marked as [AutoIncrement] as well.

Dan B

unread,
Mar 19, 2014, 7:10:47 AM3/19/14
to servic...@googlegroups.com
There's another gotcha that you should be aware of is that OrmLite expects the first property in the class to be the Id property by convention - Resharper and other tools can rearrange your properties under you when you run automated clean up on your code. (I'm not sure if this is still valid for v4)
-Dan
Reply all
Reply to author
Forward
0 new messages