I’m having a problem with Fluent NHibernate mappings, I think, and can’t quite get past how I should be setting the mapping to avoid an issue.
I have a business object (literally, a “business”), and a review object. Each Business can have multiple reviews that are created on a page in the UI. The business is a property of the Review, as follows:
public class Business
{
public virtual int BusinessId {get;set;}
public virtual DateTime LastModified {get;set;}
public virtual IList<Review> Reviews {get;set;}
[... more removed for brevity ...]
}
public class Review
{
public virtual int ReviewId {get;set;}
public virtual string ReviewText {get;set;}
public virtual Business Business {get;set;}
[... more removed for brevity ...]
}
My mappings are as follows:
public class ReviewMap : ClassMap<Review>
{
public ReviewMap()
{
WithTable("Reviews");
Id(x => x.ReviewId).TheColumnNameIs("ReviewId").GeneratedBy.Identity();
References(x => x.Business).TheColumnNameIs("BusinessId");
Map(x => x.ReviewText);
[... and so on...]
}
public class BusinessMap : ClassMap<Business>
{
public BusinessMap()
{
WithTable("Businesses");
Id(x => x.BusinessId).TheColumnNameIs("BusinessId").GeneratedBy.Identity();
Map(x => x.Name).TheColumnNameIs("BusinessName");
Map(x => x.LastModified, "LastModifiedOn");
HasMany<Review>(x => x.Reviews)
.Inverse()
.LazyLoad();
[... more removed for brevity ...]
}
}
The repository code is
public void Save(T entity)
{
using (ISession session = GetSession())
using (ITransaction tx = session.BeginTransaction())
{
session.SaveOrUpdate(entity);
tx.Commit();
}
}
In the code, I assign the properties to the Review object, and call the Repository’s Save method.
The problem is that since I’m not updating the Business per se, I don’t expect it to get saved–all I want is the review saved. But the code tries to save the Business as well, and I get an excption, as I haven’t set the “LastModified” property–nor do I want to, as I’m saving the REVIEW, not the business.
How should I be setting up the mapping to let this happen?
Ok, so the problem was this: the Business’s LastModified property wasn’t actually set in the actual business object, as the database allowed NULL for this property.
What that meant was that when I tried to save the review, it also tried to save the business–most likely because it recognized that the database object had no value (null) for LastModified, but by default, since LastModified is a DateTime, its value was DateTime.MinValue.
Once I updated the business table in the database so that LastModified is now NOT NULL, it works.
The unfortunate part of this is that the data I was working with got into this state without this being an issue.