开发者

Why does Id altered from 1 to 1 happen using NHibernate

I have a mapping like this

<class name="UserFileSummary" table="UserFile" lazy="false">
   <id nam开发者_JAVA百科e="FileId" column="UserFileId" type="int">
      <generator class="identity" />
   </id>...

and a property in the c# object like this

public long FileId { get; set; }

What I don't understand is why when I get an instance using

var myFile = session.Get<UserFileSummary>(id)

change a field value and then save it like this

myFile.myProperty = newValue
session.Save(myFile)

I get an error saying the the Id have been altered from 1 to 1. There are some posts around about this, but this is a simple int column (identity 1, 1). I must have made some basic error, please can anyone help out. Thanks

I've added this bit as an edit as the question turns out to be a non question

The FileId property is type long, and the mapping is type int, that is why altered from 1 to 1 is a problem.

Please give me some feedback if you want me to delete this question, thanks everyone :)


The only thing I can point out from your code is the use of Save for updating an existing entity.

You could avoid calling explicitly the Save method for an entity that's alredy present on the session. Your changes will be automatically persisted when you flush the session.

If you insist to explicitly call the update method I'd say you should use SaveOrUpdate.


First, make the setter on the property private; the project will fail to compile if you have any code that mistakenly sets it. This is a good practice anyway. But it's not foolproof because there could be code inside the class that sets it, so you'll have to check for that.

public int FileId { get; private set; }

Second, closely examine the mapping file to make sure that you haven't mapped the field twice.


The error in my case was due to the data type being a long (int64) in the database and being mapped to an int (int32) in the mapping. This meant that the real value changed whenever the object was saved, thus breaking the identifier. Thanks to everyone who helped out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜