![](/img/trans.png)
[英]fluent nhibernate nullable foreign key “null reference exception”
[英]Fluent NHibernate enforce Not Nullable on Foreign Key Reference
剛剛嘗試了一些流暢的NHibernate AutoMap慣例,並遇到了一些我無法弄清楚的問題。 我假設我只是沒有找到正確的位置...基本上嘗試在一對多關系的“多”方面強制執行NOT-NULL。 看來,使用自動化,它總是使父屬性Id在數據庫中可以為空。
我在StackOverFlow上做了一些搜索,發現了類似的問題,但是沒有任何與AutoMapping和Conventions相關的內容(除非我錯過了)。
快速舉例......
public class Group // One Group
{
public Group() { this.Jobs = new List<Job>(); }
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Job> Jobs { get; protected set; }
}
public class Job // Has many Jobs
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
// Trying to make this field not-nullable in the database.
public virtual Group Group { get; set; }
}
我以為我能夠創建像......這樣的會議
public class OneToManyConvention : IHasOneConvention
{
public void Apply(IOneToOneInstance instance)
{
// Nullable() isn't a valid method...
instance.Not.Nullable();
}
}
但似乎IOneToOnInstance沒有Nullable()方法。 我可以這樣做,如果我為Job創建一個Map文件,但試圖避免任何Map文件並堅持使用自動映射。
我在Fluent組列表中看到了這個鏈接,描述了類似的內容。
其中描述的是這樣的......
public class NotNullPropertyConvention : IPropertyConvention
{
public bool Accept(IProperty target)
{
return true;
}
public void Apply(IProperty target)
{
target.Not.Nullable();
}
}
但這提出了以下問題:1)我如何確定IProperty是一個Job(或任何子屬性,是一個回到父級的鏈接)
2)它在該頁面上提到使用它會覆蓋我的手動覆蓋,例如。 如果一個非常具體的屬性鏈接需要為NULL。 這將是一個問題(如果它仍然是一個問題,但不能先測試#1而無法測試)
有什么想法嗎? 我只是錯過了一些東西嗎?
仍然沒有去。 即使以下仍然沒有在數據庫模式中強制執行Not-Nullable ......
public class FluentConvention : IPropertyConvention { public void Apply(IPropertyInstance instance) { instance.Not.Nullable(); } }
它適用於所有其他領域......
/聳肩
有任何想法嗎?
雖然這不是我想要的答案,但我確實找到了解決方法......我正在使用NHibernate Validator程序集,並且在該程序集中有一個[NotNull]屬性。 如果我使用Validator屬性修飾了我的類,並在創建模式之前將ValidationEngine與NHibernate相關聯,那么它會將FK數據庫列標記為Not-Nullable。
public class Job // Has many Jobs { public virtual Guid Id { get; set; } public virtual string Name { get; set; } [NHibernate.Validator.Constraints.NotNull] public virtual Group Group { get; set; } }
如果有人需要NHibernate + ValidationEngine初始化的完整代碼,請告訴我。 如果有人有任何信息,仍然在尋找使用純映射約定路線的方法...
謝謝!
您可以在Fluenttly.Configure()中將自動映射屬性覆蓋為AutoMap的一部分。
所以你可以這樣做:
.Override<Job>(map => map.References(x => x.Group).Not.Nullable())
如果你有很多需要這個的課程,這並不是很方便。
編輯:您還可以在實現IAutoMappingOverride的類中指定覆蓋,如下所示:
public class JobMappingOverride : IAutoMappingOverride<Job>
{
public void Override(AutoMapping<Job> mapping)
{
mapping.References(x => x.Group).Not.Nullable();
}
}
並包括它:
.UseOverridesFromAssemblyOf<JobMappingOverride>()
這將使您的流暢配置更清潔。
似乎只對類的簡單屬性調用IPropertyConvention
。 如果您的屬性引用了另一個類,則還需要使用IReferenceConvention
。
嘗試這個:
public class FluentConvention : IPropertyConvention, IReferenceConvention
{
public void Apply(IPropertyInstance instance)
{
instance.Not.Nullable();
}
public void Apply(IManyToOneInstance instance)
{
instance.Not.Nullable();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.