CrazyCoderz
CrazyCoderz

Reputation: 1341

Nhibernate and the case of Auto Updating Entities

Best title I could come up with, A little more involved however.

// Hit the database once and get all the categories;
IQueryable<Category> qryCategoryList = _repository.Select<Category>();

// get initial parents
var parentCategories = qryCategoryList.Where(x => x.ParentCategoryId == null);
foreach (Category parentCategory in parentCategories)
{
    HttpContext.Current.Response.Write(parentCategory.CategoryName = "This should not happen");
            BuildCategoryList(qryCategoryList, parentCategory.CategoryId);
}

This line

 HttpContext.Current.Response.Write(parentCategory.CategoryName = "This should not happen");

performs this

UPDATE Categories
SET    ParentCategoryId = NULL /* @p0_0 */,
       CategoryName = '->' /* @p1_0 */,
       CategoryDescription = 'The Fruit Category' /* @p2_0 */,
       Active = 1 /* @p3_0 */,
       DateCreated = '2012-01-20T12:03:41.00' /* @p4_0 */,
       LastUpdated = '2012-01-20T12:03:41.00' /* @p5_0 */
WHERE  CategoryId = 'aa8ca9ba-663c-45c8-950b-159a28e6635d' /* @p6_0 */

I am not calling save from my repository not wanting to do an update. How is this possible?

EDIT: Here is the mapping

 public class CategoryMap : ClassMap<Category>
{
    public CategoryMap()
    {
        Table("Categories");
        LazyLoad();
        Id(x => x.CategoryId).GeneratedBy.GuidComb().Column("CategoryId");
        Map(x => x.ParentCategoryId).Column("ParentCategoryId");
        Map(x => x.CategoryName).Column("CategoryName").Not.Nullable().Length(50);
        Map(x => x.CategoryDescription).Column("CategoryDescription").Not.Nullable();
        Map(x => x.Active).Column("Active").Not.Nullable();
        Map(x => x.DateCreated).Column("DateCreated").Not.Nullable();
        Map(x => x.LastUpdated).Column("LastUpdated").Not.Nullable();
        HasMany(x => x.PostingsCategories).KeyColumn("CategoryId");
    }
}

Upvotes: 0

Views: 376

Answers (1)

Nicholas Piasecki
Nicholas Piasecki

Reputation: 25573

This usually happens when something in the mapping or object declaration doesn't quite jive with what's in the database. For example, you might have a UNIQUEIDENTIFIER in the database that's nullable but mapped that to a non-nullable Guid on an object. NHibernate selects, sees a Guid.Empty instead of a null, and says "Hey! The object changed! Whelp, reckon I should update it..."

That's just one case of how it can happen. If you post your mapping, we might be able to help you debug it a bit further.

--

Actually, I should have read it a bit further. If this is within the scope of a transaction, NHibernate will auto update any changed entities without needing an explicit call to SaveOrUpdate(). It's called autoflush and it's on by default. You'll need to set the FlushMode to Never if you want to explicitly call transaction.Commit() or session.Flush().

Upvotes: 2

Related Questions