我正在使用 NHibernate 和 HiLo 策略,我的问题是集合中对象的 ID 不是在 Session.Save() 上生成的(仅在 Transaction.Commit() 上)。例如:
ImageGallery imageGallery = imageGalleryRepository.GetById(imgGalleryId);
imageGallery.Images.Add(new Image());
imageGalleryRepository.Save(imageGallery); // Here I need to access ID propery of new image in Images collection but it's 0 until I commit transaction. Can it be done?
这是我的代码:
public abstract class Entity
{
public virtual int Id { get; set; }
}
public class ImageGallery : Entity
{
public virtual IList<Image> Images { get; set; }
// ...
}
public class Image : Entity
{
public string FileName { get; set; }
public ImageGallery ImageGallery { get; set; }
// ...
}
映射:
public class ImageGalleryMap : ClassMap<ImageGallery>
{
public ImageGalleryMap()
{
Id(x => x.Id).GeneratedBy.HiLo("hibernate_unique_key", "next_hi_image_gallery", "10");
HasMany(x => x.Images).
Cascade.All().
KeyColumn("GalleryId").
Inverse().
Fetch.Join();
}
}
public class GalleryImageMap : ClassMap<GalleryImage>
{
public GalleryImageMap()
{
Id(x => x.Id).GeneratedBy.HiLo("hibernate_unique_key", "next_hi_image", "10");
Map(x => x.FileName);
References(x => x.ImageGallery).Column("GalleryId");
}
}