NHibernate - access the ID of an associated object without lazy loading the whole object

前端 未结 3 1345
北恋
北恋 2020-12-16 05:04

I have two associated business objects - A and B. the association is (A->B)many-to-one, with B.Id a foreign key in A (so A has A.B_id in the DB).

I\'m using lazy=tru

3条回答
  •  被撕碎了的回忆
    2020-12-16 05:22

    If you are using NHibernate 3.2 or later, you could use the following code to get the id of associated object without another roundtrip to database to load the whole object:

    using NHibernate.Proxy;
    ...
    object id = null;
    if (obj.IsProxy()) // obj is the object you want to get its identifier.
    {
        var proxy = obj as INHibernateProxy;
        if (proxy != null)
        {
            var li = proxy.HibernateLazyInitializer;
            if (li != null) 
                id = li.Identifier;
        }
    }
    

提交回复
热议问题