SchemaUpdate generates duplicate foreign keys

We have a typical web application that its data access layer is written using Castle ActiveRecord. Castle ActiveRecord exposes NHibernate’s SchemUpdate feature. This feature lets us to upgrade schema/database with current changes in domain entities.

One odd problem with SchemaUpdate was that in many cases it was generating foreign keys again without any change in domain entity. After some search I found that if you did not specify foreign key names explicitly, NHibernate generates them randomly. So in update progress becuase name of existing foreign keys are not equal to new generated ones, they are generated again as duplicate.

Solution is very easy. Wherever you use BelognsTo you must specify a fixed name for ForeignKey attribute. This way a none random name is generated for foreign key names. Be aware that foreign key names must be unique across a database.

An example:

[BelongsTo(Column="Owner_ID", ForeignKey="FK_Owner_ID")]
public virtual SomeType Owner { set; get; }

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *