我正在尝试使用 NHibernate 3.3.3 将我的 FluentNHibernate 映射转换为 NHibernate 映射代码。目标是升级到 NHibernate 3.3.3 并减少分发的程序集数量。
然而,当我编译并运行时,出现以下异常:
NHibernate.MappingException: Multi-columns property can't be mapped through single-column API.
XML 映射 FluentNHibernate 让我看起来像这样:
<many-to-one cascade="none" class="TextDto" fetch="join" lazy="false" name="Name" not-found="ignore">
<column name="NameTextId" unique="false" />
<column name="LanguageId" unique="false" />
</many-to-one>
这是我的新代码映射:
this.ManyToOne(u => u.Name, c =>
{
c.Cascade(Cascade.None);
c.Class(typeof(TextDto));
c.Columns(
x =>
{
x.Name("NameTextId");
x.Unique(false);
},
x =>
{
x.Name("LanguageId");
x.Unique(false);
});
c.Fetch(FetchKind.Join);
c.Lazy(LazyRelation.NoLazy);
c.NotFound(NotFoundMode.Ignore);
c.Unique(false);
});
这是旧的 FluentNHibernate 映射:
References(x => x.Name)
.Columns("NameTextId", "LanguageId")
.Cascade.None()
.Fetch.Join()
.NotFound.Ignore()
.Not.Unique()
.Not.LazyLoad();
为了完整性,涉及的属性类型:
public class TextDto
{
public TextCompositeId Id { get; set; }
public string PluralText { get; set; }
public string SingularText { get; set; }
public override bool Equals(object obj)
{
var text = (TextDto)obj;
if (text == null) return false;
return this.Id.Equals(text.Id);
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
以及实体中属性的示例:
public class CharacteristicValue
{
public CharacteristicValueCompositeId Id { get; set; }
public TextDto Name { get; set; }
public string LanguageIdentity { get; set; }
public string Value
{
get
{
string value = null;
if (this.ValueMultilingual != null) return this.ValueMultilingual.SingularText;
else if (!string.IsNullOrEmpty(this.ValueMeta)) return this.ValueMeta;
return value;
}
}
public TextDto ValueMultilingual { get; set; }
public string ValueMeta { get; set; }
public override bool Equals(object obj)
{
if (obj == null) return false;
if (object.ReferenceEquals(this, obj)) return true;
CharacteristicValue characteristicValue = obj as CharacteristicValue;
if (characteristicValue == null) return false;
if (this.Id != characteristicValue.Id) return false;
return true;
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
那么,我如何获得以前使用 FluentNHibernate 而使用 NHiberbate 的映射代码的 xml 映射?
最佳答案
在您的映射中,从 ManyToOne
映射中删除 c.Unique(false);
。我们现在将此设置应用于每一列。
this.ManyToOne(u => u.Name, c =>
{
... // the same as above
// c.Unique(false); // it is setting now related to columns
});
你会收到
<many-to-one name="Name" class="TextDto" fetch="join" lazy="false" not-found="ignore">
<column name="NameTextId" unique="true" />
<column name="LanguageId" />
</many-to-one>
如果您要更改其中一列的唯一性:
x =>
{
x.Name("NameTextId");
x.Unique(true); // change here
},
唯一约束将添加到该列:
<column name="NameTextId" unique="true" />
关于NHibernate 多列 ManyToOne 映射与映射代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17165977/