【问题标题】:How to get list of ViewModel from database?如何从数据库中获取 ViewModel 列表?
【发布时间】:2015-12-11 17:45:23
【问题描述】:

我有一个视图模型类,用于获取客户列表及其报价列表。

餐厅视图模型

public class RestaurantsListVM
{
    public Client client { get; set; }
    public List<Offer> offers { get; set}; 
}

客户端模型

public class Client
{
     public Guid Id { get; set; }
     public String RestaurantName { get; set; }
}

报价模式

public class Offer
{
     public Guid Id { get; set; }
     public String OfferName { get; set; }
     public decimal OfferPercentage { get; set; }

在我的数据库中,我有一个 ClientOffer 表,它还将客户与他们的报价对应起来,例如:

***"ClientOfferId,ClientId,OfferId"***

所以我创建了这个函数来从数据库中检索数据。

public List<RestaurantsListVM> GetRestaurants()
{
     List<RestaurantsListVM> restaurantlist = new List<RestaurantsListVM>();

     var clients = new Client().GetClients();

     foreach (Client c in clients)
     {
         RestaurantsListVM restaurantdetails = new RestaurantsListVM();
         restaurantdetails.client = c;
         restaurantdetails.offers = new Offer().GetOffers(c.Id);
         restaurantlist.Add(restaurantdetails);
     }

     return restaurantlist;
 }

它工作正常。但问题是它在 sql server 中一次又一次地执行查询,同时检索每个客户端提供,并且性能下降。

我应该如何提高我的代码效率以获得更好的性能?

【问题讨论】:

  • 检索所有餐厅及其优惠大约需要 10 秒。

标签: c# model-view-controller viewmodel asp.net-mvc-viewmodel


【解决方案1】:

您需要一个 LINQ 查询,该查询将在一个 SQL 查询中连接表。目前,您获得所有客户,然后为每个客户获得他们的报价。比如:

var clientOffers = (from cli in dbContext.Clients

join cli_ofr in dbContext.ClientOffer
on cli.ClientId
equals cli_ofr.ClientId

join ofr in dbContext.Offers
on cli_ofr.OfferId
equals ofr.OfferId

select new {
Client = new Client { Guid = cli.Guid...},
Offer = new Offer { Guid = ofr.Guid... }
}).toList();

这将生成一个 SQL 查询,该查询将返回创建视图模型所需的所有数据。

【讨论】:

  • 谢谢。这对我很有帮助。
【解决方案2】:

为什么不为 ClientOffer 创建模型?

public class ClientOffer
    {
     public Guid client_id { get; set; }
     [ForeignKey("client_id")]
     public Client client { get; set; }
     public Guid offer_id { get; set; }
     [ForeignKey("offer_id")]
     public Offer offer { get; set; }
    }

在您的客户模型中,您可以添加优惠集合

public class Client
    {
     public Guid Id { get; set; }
     public String RestaurantName { get; set; }
     public ICollection<ClientOffer> offers { get; set; }
    }

因此,您可以从您的模型客户端循环提供属性

【讨论】:

  • 是的。您的代码也可以正常工作。但是它对数据库生成了太多的 SQL 查询来检索这些数据。有没有其他方法可以达到同样的效果?
猜你喜欢
  • 2020-05-04
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-16
  • 2014-08-09
相关资源
最近更新 更多