Nhibernate中类内部的空值和空值属性

时间:2013-03-12 05:12:37

标签: c# nhibernate

我使用nHibernate从类映射中获取空值,请参阅下面的内容:

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

Repository.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

为什么类Indicador中的属性值为null并且在类外部加载?我做错了什么?

1 个答案:

答案 0 :(得分:2)

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

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

您正尝试在构造函数中访问并显示属性值,以查找当时甚至未绑定到数据库的对象。为什么要为此属性设置特定值?

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

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