Search code examples
sqlitefluent-nhibernate

How to force nHibernate to update referencing objects automaticly?


So I got two fluent nHibernate Tables in sqlite:

public class Product
{
    public virtual long Id { get; set; }
    public virtual Exchange Exchange { get; set; }
}

public class ProductMap : ClassMap<Product>
{
    public ProductMap()
    {
        Id(x => x.Id);
        References(x => x.Exchange);
    }
}   

public class Exchange
{
    public Exchange()
    {
        Products = new List<Product>();
    }
    public virtual long Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Product> Products { get; set; }

}

public class ExchangeMap : ClassMap<Exchange>
{
    public ExchangeMap()
    {
        Id(x => x.Id);
        Map(x => x.Name).Unique();          
        HasMany(x => x.Products)
          .Inverse()
          .Cascade.All();

    }
}   

I set the Exchange of a product like this:

using (var transaction = m_DbSession.BeginTransaction())
{
    try
    {
        var exchanges = (from p in m_DbSession.Query<Exchange>() select p).ToList()
        product.Exchange = (from p in exchanges
                            where p.Name == exchangeName
                            select p).FirstOrDefault();
    }
    catch (Exception ex)
    {
        new ExceptionDialog(ex, "Set Exchange").Show();
    }
    
    m_DbSession.SaveOrUpdate(m_DBProduct);
    transaction.Commit();
}

The Sqlite database is updated, but it seems like the Exchanges are not updated correctly, because when I want to do this:

var notCorrect = (from ex in m_DbSession.Query<Exchange>() orderby ex.Name select ex).ToList();
Debug.WriteLine(notCorrect[0].Products.Count);

the new Product was not added to the 'exchange-side' of the transaction is not reprented. This means that The product count is 0 (1 would be correct).

When I restart my program everything is correct.

So why does the content of my Exchanges do not update without restarting?

When I update the Product-List of my Exchange by myself in the transaction like this:

product.Exchange.Products.Add(product);

It works too. But this could not be the answer, coudnt it? I think there has to be a way to force nHibernate to update its references by itself?

If the question is not clear please ask me. Im no native speaker so I had a hard time explaining everything. Ill update the question.


Solution

  • With the help of What's the best way to refresh entities in nhibernate I found out that the solution to my problem is. Its:

    Session.Refresh
    

    So the way I take care for the the Product-List of my releated Exchange is to call Session.Refresh after saving and commiting the product. Like this:

    private void Save()
    {
        using (var transaction = m_DbSession.BeginTransaction())
        {
            m_DbSession.SaveOrUpdate(product);
            transaction.Commit();
            m_DbSession.Refresh(product);
        }
    }