ManyToOne nullable relationship, how to achieve that?

ManyToOne nullable relationship, how to achieve that?

Old forum URL: forums.lhotka.net/forums/t/9162.aspx


elber73 posted on Friday, July 02, 2010

Hello, when we have the follow scenario:

  1. We have a SwitchableObject named Destination maped to a table.
  2. We have a EditableRoot named Country maped to another table.
  3. The SwitchableObject Destination have a property CountryMember that is a ManyToOne relation pointing to the Country object.
  4. The FK on Destination table pointing to Country table is a nullable index.

COUNTRY (ER) <--(nullable FK)-- DESTINATION (ECL + SWObj)

What is the best approach to write the CountryMember on Destination object, as we can access some properties of its parent? (we have the problem that the FK is nullable, and sometimes the parent will exists and sometimes the parent will not exists).

For example:

private static readonly PropertyInfo< Country > _countryMemberProperty = RegisterProperty< Country >(p => p.CountryMember, Csla.RelationshipTypes.Child);
public Country CountryMember {
  get {
    if(!FieldManager.FieldExists(_countryMemberProperty)) {
      var criteria = new Sample_FK_Nullable.Library.CountryCriteria {};
      if(CountryFk.HasValue) criteria.Identification = CountryFk.Value;
      if(IsNew || (!CountryFk.HasValue) || !Sample_FK_Nullable.Library.Country.Exists(criteria))
        LoadProperty(_countryMemberProperty, Sample_FK_Nullable.Library.Country.NewCountry());
      else
        LoadProperty(_countryMemberProperty, Sample_FK_Nullable.Library.Country.GetByIdentification(CountryFk.Value));
    }
    return GetProperty(_countryMemberProperty);
  }
}

When the parent object exists, it is ok, we load its reference, but what to do when no parent exists?

create a new one and load its new reference
?
(problemreally we dont want to create a new parent, only access its properties, but only if it exists)  

load null into the property
?
(problem: if we load null value we will have to validate if its null all the times before we can access its Country properties)

What people do in that case?

Thank you very much.

RobBracken replied on Friday, July 02, 2010

I wouldn't be happy if the object created a new "parent" object automatically. My view is that if the key value is null, the property should return a null object, not create a new one.

Copyright (c) Marimer LLC