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 Product
or ProductMap
class I believe. The issue is with the ProductCategory
map.
That is what is creating the ProductCategoryId
column in the database.
public class ProductCategoryMap : ClassMap<ProductCategory>
{
public ProductCategoryMap()
{
Id(x => x.Id);
// Other mappings
HasMany(x => x.Products).Inverse().Cascade.AllDeleteOrphan();
}
}
This mapping wasn't able to tell that it was supposed to be using the existing CategoryId
column. Specifying it on the mapping file, or even renaming my Category
property on the Product
class to ProductCategory
forces it to stop creating a different column.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.