當使用單向關聯時,NHibernate阻止我使用由外鍵和列組成的唯一索引。使用NHibernate的唯一複合索引
//The classes
public class Method
{
public virtual Guid ID { get; private set; }
public virtual List<MethodParameter> Parameters { get; private set; }
public Method()
{
this.Parameters = new List<MethodParameter>();
}
}
public class MethodParameter
{
public virtual Guid ID { get; private set; }
public virtual string Name { get; private set; }
protected MethodParameter() { }
public MethodParameter(Method method, string name)
{
this.Name = name;
method.Parameters.Add(this);
}
}
//The mappings
public class MAP_Method : ClassMap<Method>
{
public MAP_Method()
{
this.Table("[Method]");
this.Id(x => x.ID).Access.BackingField().GeneratedBy.GuidComb();
this.HasMany(x => x.Parameters)
.Access.BackingField()
.KeyColumn("[Method]")
.Not.LazyLoad()
.Cascade.AllDeleteOrphan();
}
}
public class MAP_MethodParameter : ClassMap<MethodParameter>
{
public MAP_MethodParameter()
{
this.Table("[MethodParameter]");
this.Map(x => x.Name).Length(50).Not.Nullable();
}
}
如果我創建了有兩個MethodParameters(名稱:x和名稱爲:y)一個方法實例,然後是沒有問題的。但是,如果我使用相同的MethodParameter名稱在同一個事務中創建兩個Method實例,那麼我會得到唯一的索引違例。
這是因爲我在[MethodParameter]([Method] ASC,[Name] ASC)上有一個唯一索引,並且單向關聯NHibernate首先爲[Method]列插入了帶NULL的子表,然後返回並用正確的[Method]值更新行。 (Method,x「)(Method2,」x「)(Method2,」x「)結尾的兩個Method實例具有相同的MethodParameter名稱時,顯然這是一個問題。 「x」)
據我所知,這是設計的行爲,但似乎我被迫要麼有雙向反向關聯,要麼從數據庫中刪除唯一索引。有沒有辦法讓NHibernate在插入而不是插入NULL然後更新時插入正確的[Method] ID?
似乎所有我要做的就是升級到NH,而不是更高版本.KeyNullable()足以解決問題 – 2012-08-06 11:48:27