开发者

What is the best way to retrieve/save log entries linked to other entities through NHibernate?

Disclaimer: I'm outlining simplified picture to emphasize main point of my question.

The application I'm working on maintains a set of resources. We have a corresponding table and mapped entity in NHibernate. Each resource identified by integer id. Also we have user table and corresponding entity to maintain user profiles.

We need to log user accesses to the application and retrieve access history. For repository class we have to introduce 2 methods:

  1. IEnumerable GetUserLog(User user) to retrieve user access history order by date in descending order and
  2. void WriteLogEntry(User user, Resource resource) to write new entry

I have tried to simply define LogEntry entity as following:

public class LogEntry
{
     public virtual User User {get; set;}
     public virtual Resource Resource {get; set;}
     public virtual DateTime Date {get; set;}
}

and map it using Fluent NHibernate as usually. To retrieve/update log entries we can simply use

Session.Query<LogEntry>().Where(entry => entry.User = currentUser).OrderByDesc(entry => entry.Date)
Session.Save(new LogEntry() {
    User = currentUser,
    Resource = resource,
    Date = DateTime.Now
})

This is the most convenient way to deal with this issue for us.

Problem The problem is that NHibernate requires id mapping. We have to use composite id here and the only option is to map User, Resource and Date columns because only this combination provides uniqueness. Also in case of composite id we have to override Equals and GetHashCode and all this seems to be overkill for such a simple task. Another problem that lazy loading cannot be used for id fields and it's too much as well. We do not want to load all related Resource entities in advance.

Another possible solution is to define plain class, not entity and then use SetResultTransformer(Transformers.AliasToBean()) to retrieve results. In that case we have to construct queries manually, retrieve related entities manually and this开发者_Go百科 way it's not better in general then dealing with raw connection.

I would like to ask expert opinion because I'm confident people around had similar experience and can help. Thanks in advance.

P.S. This is ASP.NET MVC application using NHibernate 3 (+ Fluent). Log information will be used to display last 5-10 resources user accessed.


have you considered introducing an Id field for LogEntry table as well?
many DBAs will recommend it and it seems like the easiest solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜