Domanda

I have the following method which is called from Ajax:

 [Authorize]
    [ValidateInput(false)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public JsonNetResult CreateOrUpdateTimeRecord(TimeRecord tr)
    {

        TimeRecord trLocal;
        if (tr.Id == -1 || tr.Id == 0)
        {
            trLocal = new TimeRecord
            {
                Description = tr.Description,
                StartTime = tr.StartTime,
                EndTime = tr.EndTime,
                User =new myTimeMvc.Models.NHibernate.Models.User {Id = tr.User.Id},// _userRepo.Get(tr.User.Id),
                Hdt = new Hdt {Id = tr.Hdt.Id}//_hdtRepo.Get(tr.Hdt.Id)
            };

            _timeRepo.Insert(trLocal);

        }
        else
        {
            trLocal = _timeRepo.Get(tr.Id);

            trLocal.Description = tr.Description;
            trLocal.StartTime = tr.StartTime;
            trLocal.EndTime = tr.EndTime;

            _timeRepo.Update(trLocal);
        }

        ...
    }

As you can see my TimeRecord has a reference to User and Hdt. Now I started to work with NHibernate Profiler which complains when I resolve my properties by loading them from their coresponding repositories. Which is clear to me since I actually don't need to query the database for that since I have the ID's for this objects.

 User = _userRepo.Get(tr.User.Id),
 Hdt = _hdtRepo.Get(tr.Hdt.Id)

But I'm not 100% sure if I can use this instead:

User =new myTimeMvc.Models.NHibernate.Models.User {Id = tr.User.Id},,
Hdt = new Hdt {Id = tr.Hdt.Id}

I guess NHibernate lazy proxies work the same way since they only contain just the ID of the related object and load the rest when it is needed. Do I have to attach this "new" oject anyway to my session? Can someone tell me what is the correct way to do this?

Cheers, Stefan

È stato utile?

Soluzione

There are a few ways how to achieve that. One of them could be using the Load() method. Check Ayendes post: NHibernate – The difference between Get, Load and querying by id, an extract:

Load will never return null. It will always return an entity or throw an exception. Because that is the contract that we have we it, it is permissible for Load to not hit the database when you call it, it is free to return a proxy instead.

Other words, we can do something like this

User = _userRepo.Load(tr.User.Id),
Hdt = _hdtRepo.Load(tr.Hdt.Id)

Where the Load would be encapsulating the session.Load()

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top