开发者

NHibernate - code example for update

I've been trying all day to get one of my object to be saved with versions but to no avail. Please point out what I'm doing wrong, as I've tried SaveOrUpdate, Merge() and Update() after a Clear() call.

The business object:

 public class MappedTest  
{  
    public virtual Guid TestID { get; set; }  
    public virtual int VersionID { get; set; }  
    public virtual byte[] Content { get; set;}  
    public virtual DateTime DateSaved { get; set; }  
}  

The mapping:

<?xml version="1.0" encoding="utf-8" ?>  
<hibernate-mapping ...>  
 <class name="TestImp.Definition.MappedTest, PythonTest" table="Tests">  
  <id name="TestID" unsaved-value="00000000-0000-0000-0000-000000000000">  
  <generator class="guid"/>  
</id>  
<version name="VersionID" column="VersionID" />  
<property name="Content" column="TestObject" type="BinaryBlob"/>  
<property name="DateSaved" column="Date"/>  

`

The actual code:

using (var 开发者_开发技巧session = new Configuration().Configure().BuildSessionFactory().OpenSession())  
        {  
            using (ITransaction transaction = session.BeginTransaction())  
            {  
                if(session.Get<MappedTest>(mappedTest.TestID) == null)  
                {  
                    session.Save(mappedTest);  
                }  
                else  
                {  
                session.Clear();  
                    session.Update(mappedTest);  
                }  
                transaction.Commit();  
            }  
        }`  

Thanks.


For insert try just with:

using (var session = new Configuration().Configure().BuildSessionFactory().OpenSession())  
    {  
        MappedTest mappedTest =new MappedTest();

        using (ITransaction transaction = session.BeginTransaction())  
        {  
            session.SaveOrUpdate(mappedTest);  
            transaction.Commit();  
        }  
    }  

for update:

using (var session = new Configuration().Configure().BuildSessionFactory().OpenSession())  
    {  
        MappedTest mappedTest =session.Get<MappedTest>(..an Id..);
        mappedTest.YourProperty="newValue";

        using (ITransaction transaction = session.BeginTransaction())  
        {  
            session.SaveOrUpdate(mappedTest);  
            transaction.Commit();  
        }  
    }  

If you need it try use a session.Flush() to force database operations.


Another possibility that took me some time to realize and is not covered yet on this thread: In such case, check if your mapper is set on ReadOnly. NHibernate does not tell anything when asked to save or update with a ReadOnly mapper.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜