C# 带有Mysql连接器的实体框架选择随机实体
我在asp.net Webapi项目中将实体框架与mysql数据库连接。我们有一个表“食谱”,目标是选择一些随机食谱。首先我们选择一些含有特定成分的食谱,然后我们随机选择五个食谱。这是通过以下扩展方法实现的(仅选择随机元素)C# 带有Mysql连接器的实体框架选择随机实体,c#,mysql,asp.net,entity-framework,asp.net-web-api,C#,Mysql,Asp.net,Entity Framework,Asp.net Web Api,我在asp.net Webapi项目中将实体框架与mysql数据库连接。我们有一个表“食谱”,目标是选择一些随机食谱。首先我们选择一些含有特定成分的食谱,然后我们随机选择五个食谱。这是通过以下扩展方法实现的(仅选择随机元素) public static IEnumerable TakeRandom(此IQueryable配方,int计数,bool fastWay=true){ if(count recipe.RecipeId).ToList(); C=可能的EIDS.计数; }否则 C=reci
public static IEnumerable TakeRandom(此IQueryable配方,int计数,bool fastWay=true){
if(count recipe.RecipeId).ToList();
C=可能的EIDS.计数;
}否则
C=recipes.Max(recipe=>recipe.RecipeId);
而(左>0&&尝试rr.RecipeId==id);
if(item!=null&!take.Contains(item.RecipeId)){
take.Add(item.RecipeId);
收益回报项目;
左--;
}
尝试++;
}
}
我们目前面临着一个性能问题:食谱有配料和标签,每个都有自己的表格。这是一种多对多的关系。
目前,数据库中只有约300种配方,约800种独特成分。联接表中有5000多行。服务器响应可能需要30秒(因为我们是学生,所以在azure中使用免费的mysql数据库)。但是我不认为数据库是问题所在,因为我们查询了太多的行,而随机实体的选择不是很好。请注意,我们使用outputcaching,因此每小时只有一个用户的连接速度非常慢
我尝试了以下方法来优化性能
- :将不起作用,因为未为Mysql定义函数Guid.NewGuid()。此外,由于排序的原因,它也无法执行
- Used newid()mysql函数:我很清楚orderby不是一个性能良好的解决方案
提前感谢从
possibleIds
中随机选择,比如说randomIds
,然后使用randomIds.Contains(…)
一次获取所有数据。从possibleIds
中随机选择,比如说randomIds
,然后使用randomIds.Contains(…)
一次获取所有数据。
public static IEnumerable<Recipe> TakeRandom(this IQueryable<Recipe> recipes, int count, bool fastWay = true) {
if (count <= 0)
throw new Exception("Cant draw a negative number of recipes");
int left = count;
int tries = 0;
ISet<int> taken = new HashSet<int>();
Random r = new Random();
int C = 0;
IList<int> possibleIds = null;
if (!fastWay) {
possibleIds = recipes.Select(recipe => recipe.RecipeId).ToList();
C = possibleIds.Count;
} else
C = recipes.Max(recipe => recipe.RecipeId);
while (left > 0 && tries < count * count) {
int id = 0;
if (!fastWay)
id = possibleIds[r.Next(C)];
else
id = r.Next(C);
var item = recipes.FirstOrDefault(rr => rr.RecipeId == id);
if (item != null && !taken.Contains(item.RecipeId)) {
taken.Add(item.RecipeId);
yield return item;
left--;
}
tries++;
}
}