1

我从使用 nHibernate 的类映射中获取空值,请参见下文:

public class IndicadorRepository : Repository<IndicadorRepository>
{
    ...
    public Indicador FindById(int indicadorId)
    {
        return _session.Get<Indicador>(indicadorId);
    }
    ...
}

存储库.cs

    public class Repository<T> where T : Repository<T>, new()
    {
        /* Properties */
        protected static T instance;
        public ISession _session;
        public static T Instance
        {
            get
            {
                if (instance == null) instance = new T();
                return instance;
            }    
        }

        /* Constructor */
        protected Repository()
        {
            this._session = SingletonSession.Session;
        }
}

SingletonSession.cs

class SingletonSession
{
    protected static ISession _session;
    public static ISession Session
    {
        get
        {
            if (_session == null)
            {
                try
                {
                    var cfg = new Configuration();
                    cfg.Configure();
                    cfg.AddAssembly(typeof(Objetivo).Assembly);
                    var schema = new SchemaUpdate(cfg);
                    schema.Execute(true, true);
                    // Get ourselves an NHibernate Session
                    var sessions = cfg.BuildSessionFactory();
                    _session = sessions.OpenSession();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            return _session;
        }
    }
}

从这里开始问题

Indicador.cs这个类是用 nhibernate 映射的。

public class Indicador : Modelo<Indicador>
{
     public virtual string Nombre { get; set;}

     /************* Constructor *************/
    public Indicador()
    {
        // Pay attention to line below
        Console.WriteLine("Property from Inside: " + Nombre); 
    }
}

SomeForm.cs

...
private void ConfigurarIndicadoresDataGrid()
{
    // Pay attention to line below
    Console.WriteLine("Property from Outside: {0}", IndicadorRepository.Instance.FindById(1).Nombre); 
}
...

输出结果:

Property from Inside:

Property from Outside: This is the name of indicador 1

为什么类内的属性值为Indicadornull,而类外的属性值是加载的?我究竟做错了什么?

4

1 回答 1

2

也许我误解了你的问题,但这似乎是一个时间问题。

Console.WriteLine("Property from Inside: " + Nombre);

您正在尝试在构造函数中访问和显示一个属性值,该对象当时甚至没有绑定到数据库。为什么要为此属性指定特定值?

 Console.WriteLine("Property from Outside: {0}", IndicadorRepository.Instance.FindById(1).Nombre); 

您正在显示刚刚从数据库加载的对象的值。它(希望)具有价值

于 2013-03-12T09:33:20.937 回答