ActiveRecord-Fu

Ok so I have some ActiveRecord Entities: Organizations and Groups. Groups belong to Organizations, and Organizations have many groups. They are defined thusly:

    [ActiveRecord("`Group`")]
    public class Group
    {
        private readonly int id = 0;
        private Organization organization;

        [PrimaryKey(Access = PropertyAccess.NosetterCamelcase)]
        public int Id
        {
            get { return id; }
        }

        [BelongsTo(NotNull=true)]
        public Organization Organization
        {
            get { return organization; }
            set { organization = value; }
        }
    }

    [ActiveRecord]
    public class Organization
    {
        private readonly int id = 0;
        private IList groups = new List();

        [PrimaryKey(Access = PropertyAccess.NosetterLowercase)]
        public int ID
        {
            get { return id; }
        }

        [HasMany(typeof(Group), Cascade=ManyRelationCascadeEnum.All)]
        public IList Groups
        {
            get { return groups; }
            set { groups = value; }
        }
    }

That’s all well and good. Notice I’m not using ActiveRecordBase and am instead using Repositories based on ActiveRecordMediator, which is terribly cool. Also notice that on Organization.Groups I’m cascading all updates/deletes/ and saves to the groups. Groovy. My problem lies in the fact that I want Organization to be solely responsible for the Organization <-> Group relation.

[Test]
public void OrganizationsCanBeCreated()
{
  Organization org = ObjectMother.GetKittitasCountyOrganization();
  Group group = ObjectMother.GetGroup(org.Owner);
  org.Groups.Add(group);

  userRepository.Create(org.Owner);
  organizationRepository.Create(org);

  FlushAndRecreateScope();

  Organization org2 = organizationRepository.FindByID(org.ID);
  Assert.AreEqual(org.ID, org2.ID);
}

This fails. Since Group.Organization has the NotNull=true attribute, the organizationRepository.Create() fails because Organization is null. And before you rip me a new one, there are other problems with this test. I know. I know. It’s probably testing at least 4 different things. If I remove the NotNull=true from Group.Organization, this works great and AR/NHibernate sets the Group.Organization correctly (but only upon reload from the database), but I want that constraint.

Should I simply remove the NotNull=true or should I edit the domain model such that adding a Group to an Organization sets the Group organization correctly.

I’ll update this post with the solution once I find it.

Leave a Comment