简体   繁体   中英

c# Fluent NHibernate one-to-many relationship object returning null

Really trying to get my head around this but cannot see the light through the trees. Probably missed something obvious!

Within the database when I create the object it works within any issues but when I try to list the values, the linking is null...

There are two objects, Question and Response . A question can have many responses so here are the models:

public class Question
{
    public int Id { get; set; }
    public int QuestionNumber { get; set; }
    public string QuestionText { get; set; }
    public IList<Response> Responses { get; set; } 

    public Question()
    {
        Responses = new List<Response>();
    }
}

public class Response
{
    public int Id { get; private set; }
    public Question Question { get; set; }
    public int ResponseValue { get; set; }
    public string ResponseText { get; set; }
}

And here are the mappings:

public class QuestionMap : ClassMap<Question>
{
    public QuestionMap()
    {
        Id(q => q.Id);
        Map(q => q.QuestionNumber);
        Map(q => q.QuestionText).Length(300).Not.Nullable();
        HasMany<Response>(q => q.Responses).Inverse().AsBag();
    }
}

public class ResponseMap : ClassMap<Response>
{
    public ResponseMap()
    {
        Id(x => x.Id);
        References<Question>(x => x.Question).Not.Nullable();
        Map(x => x.ResponseText);
        Map(x => x.ResponseValue);
    }
}

So when I use

var responses = _session.CreateCriteria(typeof(Response)).List<Response>();

and debug and look at the Question object, it is always null.

By default all relations in NHibernate are lazy. So you have two options. Set Not.LazyLoad() or Fetch strategy in your mapping for responses OR do the fetch when you are querying the database.

var responses = _session.CreateCriteria(typeof (Response))
                .SetFetchMode("Responses", NHibernate.FetchMode.Eager)
                .List();

you may need to set the fetching strategy in the mapping for responses when you use .SetFetchMode(...). Just play around with these two settings - one at a time or both

PS: By the way I am confused how exactly not.lazyload and fetch are working and posted a question about that. FluentNHibernate: LazyLoad and Fetch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM