This question already has answers here:
Fluent nHibernate: one-to-many relationship Issue
(2个答案)
6年前关闭。
我有简单的一对多关系
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()选项-但是外键被填充为空,我在这里缺少什么?

最佳答案

使用Inverse时外键为空,因为在向集合添加ProductCampaignTargeting时必须维护关系的两边:

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

这是许多NHibernate开发人员建议将集合公开为IEnumerable或只读并封装Add和Remove方法的原因之一:
void AddTarget(ProductCampaignTargeting target)
{
    target.Product = this;
    Targetings.Add(target);
}

08-06 18:45