1

I have simple one-to-many relationship

public class Product
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string Category { get; set; }
    public virtual bool Discontinued { get; set; }
    public virtual IList<ProductCampaignTargeting> Targetings { get; set; }   
}

public class ProductCampaignTargeting
{
    public virtual Guid ID { get; set; }

    public virtual int TargetType { get; set; }

    public virtual string TargetValue { get; set; }

    public virtual Product Product { get; set; }
 }

with Mapping:

class ProductCampaignTargetingMap : ClassMap<ProductCampaignTargeting>
{
    public ProductCampaignTargetingMap()
    {
        Table("campaign_targetings");
        Id(x => x.ID).GeneratedBy.Guid();

        Map(x => x.TargetType).Column("target_type");
        Map(x => x.TargetValue).Column("target_value");

        References(x => x.Product).Column("campaign_id_fk");
    }
}

class ProductMap: ClassMap<Product>
{
    public ProductMap()
    {
        Table("Product");
        Id(x => x.Id).Column("id").GeneratedBy.Guid();

        Map(x => x.Name).Column("Name");
        Map(x => x.Category);
        // check why inverse doens't work

        HasMany(x =>         x.Targetings).KeyColumn("campaign_id_fk").Cascade.AllDeleteOrphan().AsBag();
    }
}

and it is working - but the child (many) table is updated with two commands - insert and then update When i want to change it to one command I use the Inverse() option - but then The Foreign key is populated as null, what am i missing here?

briler
  • 570
  • 6
  • 21
  • I think a similar question was answered here http://stackoverflow.com/a/1454445/314763 which should give point you in the right direction – frictionlesspulley Apr 09 '13 at 10:57
  • Have you seen this question http://stackoverflow.com/questions/7935051/unidirectional-parent-child-association-not-null `.Not.KeyNullable()` – Rippo Apr 09 '13 at 11:07

1 Answers1

1

The foreign key is null when you use Inverse because you have to maintain both sides of the relationship when adding a ProductCampaignTargeting to the collection:

target.Product = product;
product.Targetings.Add(target);

This is one of the reasons that many NHibernate developers recommend exposing the collection as IEnumerable or read-only and encapsulating the Add and Remove methods:

void AddTarget(ProductCampaignTargeting target)
{
    target.Product = this;
    Targetings.Add(target);
}
Jamie Ide
  • 48,427
  • 16
  • 81
  • 117