How to associate static entity instances in a Session without database retrieval
Posted
by Michael Hedgpeth
on Stack Overflow
See other posts from Stack Overflow
or by Michael Hedgpeth
Published on 2010-02-22T20:31:07Z
Indexed on
2010/04/05
6:03 UTC
Read the original article
Hit count: 336
nhibernate
|c#
I have a simple Result class that used to be an Enum but has evolved into being its own class with its own table.
public class Result {
public static readonly Result Passed
= new Result(StatusType.Passed) { Id = [Predefined] };
public static readonly Result NotRun
= new Result(StatusType.NotRun) { Id = [Predefined] };
public static readonly Result Running
= new Result(StatusType.Running) { Id = [Predefined] };
}
Each of these predefined values has a row in the database at their predefined Guid Id.
There is then a failed result that has an instance per failure:
public class FailedResult : Result {
public FailedResult(string description) : base(StatusType.Failed) { . . . }
}
I then have an entity that has a Result:
public class Task {
public Result Result { get; set; }
}
When I save a Task, if the Result is a predefined one, I want NHibernate to know that it doesn't need to save that to the database, nor does it need to fetch it from the database; I just want it to save by Id.
The way I get around this is when I am setting up the session, I call a method to load the static entities:
protected override void OnSessionOpened(ISession session)
{
LockStaticResults(session, Result.Passed, Result.NotRun, Result.Running);
}
private static void LockStaticResults(ISession session, params Result[] results)
{
foreach (var result in results)
{
session.Load(result, result.Id);
}
}
The problem with the session.Load method call is it appears to be fetching to the database (something I don't want to do).
How could I make this so it does not fetch the database, but trusts that my static (immutable) Result instances are both up to date and a part of the session?
© Stack Overflow or respective owner