c# - 在修改与 NHibernate 的多对多关系时防止删除/插入

标签 c# .net nhibernate fluent-nhibernate composite-key

在我的域模型中,一个用户与许多地方相关联——这种关系是通过一个 UserPlace 类和一个映射(使用 FluentNHibernate)建模的,如下所示(用户有一个名为 Neighbourhood 的 UserPlace 集合:

public class UserMap : ClassMap<User>
{
    HasMany(x => x.Neighbourhood)
      .Component(c =>
        {
          c.Map(x => x.IsDefault).Not.Nullable();
          c.Map(x => x.Selected).Not.Nullable().Default("0");
          c.References(x => x.Place).Fetch.Join();
        }
      ).Not.LazyLoad().Cascade.SaveUpdate();
}

每当我修改属于用户的任何 UserPlace 实体,然后将用户保存到数据库时,该用户的所有 UserPlace 行都会被删除,然后重新插入

我认为这是因为 NHibernate 不知道如何从另一行中唯一地标识这些行。换句话说,我的映射中的组件没有这样的键。

主键可以通过组合存储这两个实体之间关系的表中的 User_id 和 Place_id 列来形成。如何使用 Fluent 设置此 key ?这会解决我看到的删除并重新插入行为吗?

编辑: 我在 NHUsers 上询问了这个问题,Fabio Maulo 建议使用 IdBag。据我所知,这在 Fluent NHibernate 中不受支持 - 并且组件不允许标识符。我还能如何映射这种多对多关系并防止删除所有重新插入所有问题?

编辑 2:这是 NH 根据我的映射生成的表格

CREATE TABLE [dbo].[User](
[Id] [uniqueidentifier] NOT NULL,
--- a bunch of unimportant fields
CONSTRAINT [PK__User] PRIMARY KEY CLUSTERED ([Id] ASC))

CREATE TABLE [dbo].[Neighbourhood](
[User_id] [uniqueidentifier] NOT NULL,
[IsDefault] [bit] NOT NULL,
[Place_id] [int] NOT NULL,
[Selected] [bit] NOT NULL)

CREATE TABLE [dbo].[Place](
[Id] [int] IDENTITY(1000,1) NOT NULL,
--- a bunch of unimportant fields
CONSTRAINT [PK_Place] PRIMARY KEY CLUSTERED ([Id] ASC))

User.Id与Neighbourhood.User_Id、Neighbourhood.Place_id与Place.Id之间存在FK关系

最佳答案

您可以像这样映射这种关系以避免您遇到的情况:

public class UserMap : ClassMap<User>
{
    HasMany(x => x.Neighbourhood)
      .KeyColumn("User_id")
      .Not.LazyLoad().Cascade.SaveUpdate();
}

public class NeighborHoodMap : ClassMap<NeighborHood>
{
    Table("Neighbourhood");
        CompositeId()
            .KeyReference(x => x.User, "User_id")
            .KeyReference(x => x.Place, "Place_id");

    Map(x => x.IsDefault).Not.Nullable();
    Map(x => x.Selected).Not.Nullable().Default("0");
}

邻里类看起来像这样:

public class NeighborHood
{
    public virtual User User { get; set; }
    public virtual Place Place { get; set; }
    public virtual bool IsDefault { get; set; }
    public virtual bool Selected { get; set; }

    public override bool Equals(object obj)
    {
       //check here to make sure these objects are equal (user_id and place_id are the same)    
    }

    public override int GetHashCode()
    {
        return User.Id.GetHashCode() ^ Place.Id.GetHashCode();
    }
}

关于c# - 在修改与 NHibernate 的多对多关系时防止删除/插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5728741/

相关文章:

c# - PropertyChanged 影响多个属性

c# - BackgroundAudioPlayer 没有开始播放

c# - NHibernate Linq Select Projection - 使用部分选择检索完整实体

c# - 相当于休眠中的 ROW_NUMBER() 函数

c# - String.Join 与字符串连接 : Code Improvement

c# - 尽管提供的服务器路径正确,打印服务器仍抛出 "Win32 error: The printer name is invalid."异常

c# - 在 C# 中以正确的方式删除特权枚举标志

c# - 无法在异步等待上复制死锁

c# - 使用 Entity Framework 6.1.1 和模拟进行异步/等待

c# - Fluent Nhibernate "invalid or incomplete configuration"在 "WCF Test Client"运行时