Let’s say I have a product class that has a Category property on it.
public class Product : Entity<int> // Base class defines the Id
{
public virtual ProductCategory Category { get; set; }
}
The mapping file is simple
public class ProductMap : ClassMap<Product>
{
public ProductMap()
{
Id(x => x.Id);
References(x => x.Category).Nullable();
}
}
Using SchemaExport.Create This created two columns in my database, ProductCategoryId and CategoryId. Given my conventions, only CategoryId should exist. Both are nullable, but only CategoryId is used. No matter what, ProductCategoryId is always null, and it is the column with the foreign key constraint on it.
Why is this? I can’t actually find any problems with the code, as far as I can tell everything works fine using the CategoryId column. I can query/save/update with or without a Category. I wouldn’t even know the other column existed if I didn’t go looking in the database, but I don’t like having a column when I don’t know what it is for. Is there a reason it is there, or is something wrong with the way I mapped a nullable reference?
Well the problem isn’t anything to do with the
ProductorProductMapclass I believe. The issue is with theProductCategorymap.That is what is creating the
ProductCategoryIdcolumn in the database.This mapping wasn’t able to tell that it was supposed to be using the existing
CategoryIdcolumn. Specifying it on the mapping file, or even renaming myCategoryproperty on theProductclass toProductCategoryforces it to stop creating a different column.