1

I have just started with nHibernate Fluent and all is going well with my associations, until I hit a location that have a StateID (which is a foreign key, see below) of null. Then I get an error "null reference exception"

on this line Console.WriteLine(location.address + ", " + location.State.state);

below:

public static void LoadLocationsFromDatabase()
{
    using (var session = NHibernateHelper.OpenSession())
    {
        // retreive all stores and display them
        using (session.BeginTransaction())
        {
            var locations = session.CreateCriteria(typeof(Location))
                .List<Location>();

            var i = 0;
            foreach (var location in locations)
            {
                i++;
                Console.WriteLine(location.address + ", " + location.State.state);
            }
        }

    }
}

public LocationMap()
{
    Id(x => x.locationID).Column("ID");
    Map(x => x.address).Column("Address");
    References(x => x.State)
  .Column("StateID")
      .Cascade.All();
}

public class State
{
    public virtual int ID { get; set; }
    public virtual String state { get; set; }
    public virtual IList<Location> Locations { get; set; }
}

I guess this value might shouldn't probably be null in the DB. StateID is a foreign key to ID on the states table, so I guess it shouldn't be allowed to be null?

Anyway I feel that my code should be able to allow for this one way or another, so how can I get around this?

1
  • Can State be null in Location? Commented Nov 23, 2011 at 15:55

1 Answer 1

1
Console.WriteLine(location.address + ", " + (location.State == null ? "Unknown" : location.State.state));
Sign up to request clarification or add additional context in comments.

1 Comment

you're a legend. Thanks very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.