简体   繁体   English

流利的NHibernate外键/级联

[英]Fluent NHibernate Foreign Key / Cascading

The problem occurs with the creation of cascading foreign keys using the following Models, where only one Model (UserAddition) knows the other (User) and there is no possibility to add a UserAddition property to the User class: 使用以下模型创建级联外键时会出现问题,其中只有一个Model(UserAddition)知道另一个(User),并且不可能将UserAddition属性添加到User类:

class User {
    public virtual Guid Id { get; set; }
    // Other fields of no relevance
}

class UserAddition {
    public virtual Guid Id { get; set; }
    public virtual User RemoteUser {get; set; }
    public virtual string AdditionalData {get; set; }
}

The generated SQL Table for UserAddition should have an foreign key to User which is set to ON DELETE CASCADE (the setting of ON UPDATE is not important). 生成的UserAddition SQL表应该有一个用户的外键,设置为ON DELETE CASCADE(ON UPDATE的设置并不重要)。

When using the following mapping class, the foreign key is always set to "No Action", even though it's specified otherwise in the mapping. 使用以下映射类时,外键始终设置为“无操作”,即使在映射中另行指定。 Am I missing something? 我错过了什么吗?

public class UserAdditionMapping : ClassMap<UserAddition>
{
    public TrainerToEmployeeMapping()
    {
        this.Id(x => x.Id);
        this.References(x => x.RemoteUser).ForeignKey().Cascade.All();
    }
}

The Database in use is an Microsoft SQL Server 11. 正在使用的数据库是Microsoft SQL Server 11。

Thanks. 谢谢。

You can Try this: 你可以尝试这个:

this.References(x => x.RemoteUser).Column("YourColumnName").Cascade.All(); this.References(x => x.RemoteUser).Column(“YourColumnName”)。Cascade.All();

The answer is here NHibernate mapping not adding ON DELETE CASCADE option to foreign key reference . 答案是这里NHibernate映射没有向外键引用添加ON DELETE CASCADE选项 A cite: 引用:

NHibernate can only generate on delete cascade constraints on inverse collections . NHibernate只能on delete cascade逆集合的 on delete cascade约束时生成。

A code snippet from NHibernate.Mapping.Collection : 来自NHibernate.Mapping.Collection的代码片段:

public virtual void Validate(IMapping mapping)
{
    if (Key.IsCascadeDeleteEnabled && (!IsInverse || !IsOneToMany))
    {
      throw new MappingException(string.Format(
          "only inverse one-to-many associations may use on-delete=\"cascade\": {0}", Role));
    }
 ...

And then, in fluent, you'd have the mapping like this: 然后,流利地说,你有这样的映射:

HasMany(x => x.UserAdditions)
   ...
   // the setting
   .ForeignKeyCascadeOnDelete()

But it would be on the inverse end, and would require to change the User class. 但它会反过来,并且需要更改User类。 I do understand that this is what you do not want (as stated above), but this is only think you can get out of the box... 我明白这是你不想要的(如上所述),但这只是认为你可以开箱即用......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM