1

我有简单的一对多关系

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; }
 }

带映射:

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();
    }
}

它正在工作 - 但是子(许多)表使用两个命令更新 - 插入然后更新 当我想将其更改为一个命令时,我使用 Inverse() 选项 - 但是外键填充为空,我在这里失踪了吗?

4

1 回答 1

1

使用 Inverse 时外键为空,因为在将 ProductCampaignTargeting 添加到集合时必须维护关系的双方:

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

这是许多 NHibernate 开发人员建议将集合公开为 IEnumerable 或只读并封装 Add 和 Remove 方法的原因之一:

void AddTarget(ProductCampaignTargeting target)
{
    target.Product = this;
    Targetings.Add(target);
}
于 2013-04-09T12:44:37.900 回答