为什么为外键创建两列?
问题描述:
比方说,我有一个产品类,它有一个类属性。为什么为外键创建两列?
public class Product : Entity<int> // Base class defines the Id
{
public virtual ProductCategory Category { get; set; }
}
映射文件是简单
public class ProductMap : ClassMap<Product>
{
public ProductMap()
{
Id(x => x.Id);
References(x => x.Category).Nullable();
}
}
使用SchemaExport.Create
这造成两列在我的数据库,ProductCategoryId
和CategoryId
。根据我的惯例,只有CategoryId
应该存在。两者都可以为空,但仅使用CategoryId
。无论如何,ProductCategoryId
始终为空,并且它是具有外键约束的列。
这是为什么?我实际上找不到代码的任何问题,只要我可以使用CategoryId列告诉一切正常。我可以查询/保存/更新有或没有类别。如果我没有去查看数据库,我甚至不知道其他列是否存在,但是当我不知道它是什么时,我不喜欢有一个列。是否有它存在的原因,或者我映射可空引用的方式有什么问题?
答
那么这个问题与Product
或ProductMap
类没什么关系。问题出在ProductCategory
地图上。
这就是在数据库中创建ProductCategoryId
列的原因。
public class ProductCategoryMap : ClassMap<ProductCategory>
{
public ProductCategoryMap()
{
Id(x => x.Id);
// Other mappings
HasMany(x => x.Products).Inverse().Cascade.AllDeleteOrphan();
}
}
该映射无法说明它应该使用现有的CategoryId
列。在映射文件上指定它,甚至将Product
类中的Category
属性重命名为ProductCategory
,强制它停止创建不同的列。