c# - 简单的一对多 fluent-nhibernate

标签 c# mysql nhibernate fluent-nhibernate

<分区>

我有简单的一对多关系

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() 选项——但随后外键被填充为 null,我在这里缺少什么?

最佳答案

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

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

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

void AddTarget(ProductCampaignTargeting target)
{
    target.Product = this;
    Targetings.Add(target);
}

关于c# - 简单的一对多 fluent-nhibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15899755/

相关文章:

javascript - 如何使用下拉列表添加日期?

c# - 如何首先在数据库中扩展类 ASP MVC 5

php - 1 个操作中的 3 个查询取决于每个查询

c# - Count=1 的此 SqlParameterCollection 的索引 1 无效

c# - 在 Fluent NHibernate 自动映射中自引用多对多关系自动映射到 1 :n and not n:n

.net - Fluent NHibernate Cascade 问题 - 尝试插入 NULL ID

c# - Asp.net mvc 限制特定用户访问文件夹内容

c# - MVC Azure无法找到具有默认路由的 View 或主控,但可以在本地工作

php - 具有多个子查询的 MySQL 查询,每个子查询具有不同的连接类型

php - PHP 中的 rand() 函数问题