C# 如何从数据库中获取ViewModel列表?
我有一个视图模型类,用于获取客户列表及其报价列表 餐厅视图模型C# 如何从数据库中获取ViewModel列表?,c#,model-view-controller,viewmodel,asp.net-mvc-viewmodel,C#,Model View Controller,Viewmodel,Asp.net Mvc Viewmodel,我有一个视图模型类,用于获取客户列表及其报价列表 餐厅视图模型 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 { g
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; }
提供型号
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;
}
public List GetRestaurants()
{
List restaurantlist=新建列表();
var clients=new Client().GetClients();
foreach(客户端中的客户端c)
{
RestaurantListVM restaurantdetails=新的RestaurantListVM();
restaurantdetails.client=c;
restaurantdetails.offers=newoffer().GetOffers(c.Id);
restaurantlist.Add(restaurantdetails);
}
返回餐厅列表;
}
它工作得很好。但问题是,在检索每个客户机提供的服务时,sql server会一次又一次地执行查询,性能会下降
我应该如何提高代码效率以获得更好的性能?为什么不为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; }
}
公共类客户端
{
公共Guid Id{get;set;}
公共字符串RestaurantName{get;set;}
公共ICollection提供{get;set;}
}
因此,您可以从模型客户机循环属性提供您需要一个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查询,该查询将返回创建视图模型所需的所有数据。检索所有餐厅及其报价大约需要10秒。谢谢。这对我很有帮助。你的代码也在工作。但是它对数据库生成了太多的SQL查询来检索这些数据。有没有其他方法可以达到同样的效果?