Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7529029
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T04:32:51+00:00 2026-05-30T04:32:51+00:00

Imagine a database table that looks like this: create table [dbo].[user] ( id int

  • 0

Imagine a database table that looks like this:

create table [dbo].[user]
(
    id int IDENTITY(1,1),
    username varchar(50) NOT NULL,
    firstname varchar(20) NOT NULL,
    lastname varchar(30) NOT NULL,
    currentid int NULL,
    processedby varchar(50) NOT NULL,
    processeddate varchar(50) NOT NULL
    processedaction varchar(50) NOT NULL
)

What I want to do is to setup NHibernate to load it into my user object, but I only want the current version of the object “user” to be brought back. I know how to do a SQL select to do this on my own, and I feel as if there’s something in nHibernate with the usage of triggers and event listeners, but can anyone tell me how to implement the nHibernate repository so I can:

  • {Repository}.GetCurrent(id) <- pass it any of the ids that are assigned to any of the historical or the current record, and get back the current object.
  • {Repository}.Save(user) <- I want to always insert the changes to a new row, and then update the old versions to link back to the new id.

Edit

So, there’s some confusion here, and maybe I explained it wrong… What I’m trying to do is this, in regards to always getting the current record back…

Select uc.*
FROM User uo
JOIN User uc on uo.currentid=uc.id
WHERE uo.id==:id

But, I don’t want to expose “CurrentID” to my object model, since it has no bearing on the rest of the system, IMHO. In the above SQL statement, uo is considered the “original” object set, and uc is considered the current object in the system.


Edit #2:

Looking at this as a possible solution.
http://ayende.com/blog/4196/append-only-models-with-nhibernate

I’m honestly being pigheaded, as I’m thinking about this backward. In this way of running a database, the autoincrementing field should be the version field, and the “id” field should be whatever the autoincrementer’s value has at the time of the initial insert.


Answer:

I don’t want to take @Firo’s fury, and I’m not going to remove it from him, as he took me down the right path… what I wound up with was:

  1. Created a base generic class with two types given
    a. type of the object’s “ID”
    b. type of the object itself.
  2. instantiate all classes.
  3. create a generic interface IRepository class with a type of the object to store/retrieve.
  4. create an abstract generic class with a type of the object to store/retrieve.
  5. create a concrete implementation class for each type to store/retrieve.
  6. inside of the create/update, the procedure looks like:

    Type Commit(Type item)
    {
        var clone = item.DeepClone();
        _Session.Evict(item);
        clone.Id = 0;
        clone.ProcessedDate = DateTime.Now;
        if (clone.Action.HasValue)
        {
            if (clone.Action == ProcessedAction.Create)
                clone.Action = ProcessedAction.Update;
        }
        else
        {
            clone.Action = ProcessedAction.Create;
        }
        clone.ProcessedBy = UserRepos.Where(u => u.Username == System.Threading.Thread.CurrentPrincipal.Identity.Name).First().Current;
        var savedItem = (_Session.Merge(clone) as Type);
    
        _Session.CreateQuery("UPDATE Type SET CurrentID = :newID where ID=:newID OR CurrentID=:oldID")
            .SetParameter("newID", savedItem.Id)
            .SetParameter("oldID", item.Id)
            .ExecuteUpdate();
    
        return savedItem;
    }
    
  7. In the delete method, we simply update the {object}.Action = ProcessedAction.Delete

I wanted to do this another way, but realizing we need to eventually do historical comparisons, we weren’t able to ask nHibernate to filter the deleted objects, as the users will want to see that. We’ll create a business facade to take care of the deleted records.

Again, much thanks to @Firo for his help with this.

So, with all that, I can finally do this:

var result = {Repository}.Where(obj => obj.Id == {objectID from caller}).FirstOrDefault();
if (result != null)
{
    return result.Current;
}
else
{
    return null;
}

and always get my current object back for any requesting ID. Hope it helps someone that is in my situation.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T04:32:52+00:00Added an answer on May 30, 2026 at 4:32 am

    in mapping if you use FluentNHibernate

    public UserMap : ClassMap<User>
    {
        public UserMap()
        {
            Where("id = currentid"); // always bring back the most recent
        }
    }
    
    // in Userrepository
    public void Update(User user)
    {
        var clone = user.Clone();
        session.Evict(user);  // to prevent flushing the changes
        var newId = session.Save(clone);
        session.CreateQuery("UPDATE User u SET u.currentid = :current")  // <-- hql
            .SetParameter("current", newId)
            .ExecuteUpdate();
    }
    

    objectgraphs are a lot trickier with this simple code. I would then do one of the following:

    • use NHibernate.Envers to store auditing information for me
    • explicitly creating new entities in BL code

    i once saw an append-only-model doing something like the following

    // UserBase is there to ensure that all others referencing the User doesnt have to update because user properties changed
    class UserBase
    {
        public virtual int Id { get; set; }
        public virtual ICollection<PersonDetails> AllDetails { get; private set; }
        public virtual PersonDetails CurrentDetails
        {
            get { return _currentDetauils; }
            set { _currentDetauils = value; AllDetails.Add(value); }
        }
    
        // same as above
        public virtual ICollection<ConfigDetails> AllConfigs { get; set; }
    }
    
    class Order
    {
        public virtual int Id { get; set; }
        public virtual UserBase User { get; set; }
    
        public virtual IList<OrderDetail> AllDetails { get; private set; }
        public virtual IList<OrderDetail> ActiveDetails { get; private set; }
    
        public virtual void Add(OrderDetail detail)
        {
            AllDetails.Add(detail);
            ActiveDetails.Add(detail);
        }
        public virtual void Delete(OrderDetail detail)
        {
            detail.Active = false;
            ActiveDetails.Remove(detail);
        }
    }
    
    class OrderDetail
    {
        public virtual int Id { get; set; }
        public virtual Order Parent { get; set; }
    
        public virtual bool Active { get; set; }
    }
    
    class OrderMap : ClassMap<Order>
    {
        public OrderMap()
        {
            HasMany(o => o.AllDetails);
            HasMany(o => o.ActiveDetails).Where("active=1");
        }
    }
    
    // somewhere
    public void UpdateTaxCharge(OrderDetail detail, TaxCharge charge)
    {
        var clone = detail.Clone();
        clone.TaxCharge = charge;
        detail.Order.Delete(detail);
        detail.Order.Add(clone);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a table in SQL Server 2008 that looks kind of like this:
I've got a query that presently looks something like this (I'll simplify it to
Given the table: CREATE TABLE Table1 ( UniqueID int IDENTITY(1,1) ...etc ) Now why
Imagine you have a database table that stores a list of people. You want
Imagine the following database: Table 'companies' has fields id, name and flagship_product_id. Table 'products'
What is the best way to track changes in a database table? Imagine you
Please imagine this small database... Diagram removed dead ImageShack link - volunteer database diagram
I've a HTML file that shows to the user the contents of a database
I have an old database that I am inheriting. The access rights are not
Not sure exactly how to explain this but Imaging you have a table with

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.