一點背景知識:Fluent NHibernate:HasMany插入或更新的外鍵是如何設置的?
我有一個存儲需要被保存到數據庫許多Rule
信息SomeCollection
許多實例。數據庫中的每個Rule
都有一個自動遞增的ID(PK)和一個自定義RuleId
。 Rule
表也包含一個外鍵,它是集合的ID。 Rule
表在RuleId
和CollectionId
上都包含唯一約束。
問:
如何當
HasMany
映射的外鍵插入到表中,它是孩子之後更新的插入?我要求在下面的消息中顯示爲空,但我知道這些值已設置爲如果以上是真或假,我如何執行多列唯一約束並避免以下詳細說明的問題。
當我設置強制唯一約束在SomeCollectionMapping
,我得到以下違規:
FCE檢測信息:System.Data.SqlClient.SqlException(0x80131904): 違反UNIQUE KEY約束' UQ__supporte__4D7ABD34DC8C8A20' 。 無法在對象'dbo.rules'中插入重複鍵。 重複的鍵值是(123,NULL)。
的數據是嘗試插入是:
123, myId1
123, myId2
如果我省略線:part.Not.Nullable()
和part.UniqueKey("uniqueRef")
數據成功插入到兩個表,但不強制唯一性。
即使使用Fluent NHibernate的插入失敗,我也可以使用Microsoft SQl Server Management Studio插入數據而沒有問題,並且多列約束工作正常。
SomeCollection.cs
internal class SomeCollection
{
public SomeCollection()
{
this.CollectionId = string.Empty;
this.CollectionName = string.Empty;
this.Rules = new List<Rule>();
}
public virtual string CollectionId { get; set; }
public virtual string CollectionName { get; set; }
public virtual IList<Rule> Rules { get; set; }
}
Rule.cs
internal class Rule
{
public Rule()
{
this.DisplayName = string.Empty;
this.RuleId = string.Empty;
this.MyValue = 0;
}
public virtual string DisplayName { get; set; }
public virtual string RuleId { get; set; }
public virtual int MyValue { get; set; }
}
SomeCollectionMapping.cs
internal sealed class SomeCollectionMapping : ClassMap<SomeCollection>
{
private const string TableName = "some_collections";
public SomeCollectionMapping()
{
this.Table(TableName);
this.Id(x => x.CollectionId)
.Not.Nullable()
.Column("collectionId")
.UniqueKey("abc123");
this.Map(x => x.CollectionName)
.Column("name")
.Not.Nullable();
this.HasMany<Rule>(x => x.Rules)
.KeyColumns.Add("collectionId", part =>
{
// No violations if I omit these two lines
part.Not.Nullable();
part.UniqueKey("uniqueRef");
})
.Cascade.All();
}
}
RuleMapping。CS
internal sealed class RuleMapping : ClassMap<Rule>
{
private const string TableName = "rules";
public RuleMapping()
{
this.Table(TableName);
this.Id().GeneratedBy.Increment().Unique();
this.Map(x => x.RuleId)
.Not.Nullable()
.UniqueKey("uniqueRef")
.Column("ruleId");
this.Map(x => x.DisplayName)
.Column("name")
.Not.Nullable();
this.Map(x => x.MyValue)
.Column("myValue")
.Not
.Nullable();
}
}
NHibernate的4.1.1 FluentNHibernate 2.0.3.0 SQLServer的
添加了我自己的答案,似乎已經解決了任何問題,但它並沒有真正回答我爲什麼的主要問題。隨意繼續貢獻。謝謝。 – BlackBox
你見過[this](/ q/11468668/1178314)嗎? –