开发者

Castle ActiveRecord - How do I know if an object instance is transient?

The title pretty means what i'm trying to do. There is a way to kno开发者_StackOverflow社区w if an object instance is transient? (Or, at least, was not saved yet?)

Thank you all!

PS.: Not using Exists method.


Usually this is done comparing the value of the entity's PK property with the defined unsaved-value. The most common case is having an int PK without a defined unsaved-value, e.g.:

[PrimaryKey]
public virtual int Id {get;set;}

In this case the unsaved-value is 0, so you can just compare the value of Id with 0 to find out if it's transient or not.

If you want to do this more generically, you can get the unsaved-value from the ActiveRecord model and compare against that using reflection, e.g. (untested!):

var entity = new MyEntity();
var pk = ActiveRecordModel.GetModel(typeof(MyEntity)).PrimaryKey;
var unsavedValue = pk.PrimaryKeyAtt.UnsavedValue;
var convertedUnsavedValue = Convert.ChangeType(unsavedValue, pk.Property.PropertyType);
var pkValue = pk.Property.GetValue(aform, null);
var transient = Equals(convertedUnsavedValue, pkValue);

This will probably fail in the face of null UnsavedValues (in that case you should compare with the default value of the PK type), but it should get you started.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜