假设我有以下案例。有两个表Counterparties
和Events
。一个交易对手可以有 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 在检查最新事件时会为每个交易对手执行单独的数据库查询。
问题是:我能做些什么来提高性能?