NHibernate的性能和一对多的关系

时间:2012-09-23 19:16:10

标签: performance nhibernate fluent-nhibernate

假设我有以下案例。有两个表CounterpartiesEvents。一个交易对手可以有0个,1个或更多相关事件。

我想用最新的事件获得交易对手列表以显示id DataGrid,所以我创建了:

两个实体:

public class Counterparty
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }

    public virtual IList<Event> Events { get; set; }

    public Counterparty()
    {
        Events = new List<Event>();
    }
} 

public class Event
{
    public virtual int Id { get; set; }
    public virtual DateTime EventDate { get; set; }
    public virtual string Description { get; set; }
    public virtual Counterparty Counterparty { get; set; }
}

两个映射:

public class CounterpartyMap : ClassMap<Counteparty>
{
    public CounterpartyMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
        HasMany<Event>(x => x.Events);
    }
}

public class EventMap : ClassMap<Event>
{
    public Event()
    {
        Id(x => x.Id);
        Map(x => x.EventDate);
        Map(x => x.Description);
        Reference(x => x.Counterparty);
    }
}

包含Counterparty和最新Event

的帮助程序类
public class LastestCounterpartyEvent
{
    public Counterparty Counterparty { get; set; }
    public ScoringResult ScoringResult  { get; set; }
}

最后负责创建具有最新事件的所有对手的列表的方法:

    public IList<LastestCounterpartyEvent> All()
    {
        // Added line of code responsible for data loading
        var allCounterparties = DataContext.Session.QueryOver<Counterparty>().List();
        return allCounterparties.Select(Prepare).ToList();
    }

    private LastestCounterpartyEvent Prepare(Counterparty counterparty)
    {
        var lastestCounterpartyEvent = new LastestCounterpartyEvent {Counterparty = counterparty};
        if (counterparty.Events.Count > 0)
            lastestCounterpartyEvent.Event = 
                counterparty.Events.OrderByDescending(x => x.EventDate).First();

        return lastestCounterpartyEvent;
    }

前提是不可接受的,对于30个交易对手和10个事件数据处理需要5秒。

我认为NHiberante在检查最新事件时会为每个交易对手执行单独的数据库查询。

问题是:我可以做些什么来提升绩效?

1 个答案:

答案 0 :(得分:1)

您很可能需要在.Fetch.Subselect()映射中添加HasMany()。关于here的更多信息。但这只是猜测,请显示加载数据的代码以获得更好的答案。

您还应该将您的收藏标记为反向(.Inverse()上的HasMany()),否则您在插入新活动时会遇到问题。