对于sql server 2008 R2的每个类似物,随机和for-each

时间:2015-04-18 11:35:37

标签: c# sql asp.net-mvc asp.net-mvc-4 sql-server-2008-r2

我使用c#正确运行mvc4代码,如下所示:

        try
        {

            foreach (var spec in db.Questions)
            {
                int[] ans = db.Answers.Where(m => m.in_Id == spec.in_Id).Select(m => m.in_AnswerID).ToArray();

                Random RandString = new Random();
                foreach (var prod in db.Sheet)
                {
                    SheetAns prodAns = new SheetAns()
                    {
                         in_SheetID = prod.in_SheetID

                    };
                    SheetAns.in_AnswerID = ans[RandString.Next(0, ans.Length)];
                    db.SheetAns.Add(prodAns);
                }
            }
            db.SaveChanges();
            return "Success" ;
        }
        catch(Exception ex)
        {
            return "Fail => " + ex.Message ;
        }

此代码的执行时间很长。

我想使用sql查询或数据库的存储过程执行相同的操作。

enter image description here

我们如何将此代码转换为纯sql server 2008查询(或存储过程)?

提前谢谢你。

1 个答案:

答案 0 :(得分:0)

如何首先更改您的查询本身,以便您不再拥有"select N + 1" problem

// Your select then becomes:
var newSheetAns = 
    from spec in Questions
    join ans in Answers on spec.in_Id equals ans.in_Id into g
    from prod in Sheets
    select new SheetAns()
    {
        in_SheetID = prod.in_SheetID,
        in_AnswerID = g
            .OrderBy(x => Guid.NewGuid()) // can't "ORDER BY NEWID()" in linq.
            .Select(x => x.in_AnswerID)
            .FirstOrDefault()
    };

// Now add them. This is still going to be slow, because entity framework
// does not support bulk inserts.
db.SheetAns.AddRange(newSheetAns);
db.SaveChanges();

如果这还不够快,您可以将上述LINQ语句转换为原始SQL INSERT语句(使用ORDER BY NEWID()随机化答案ID选择)。

然后可以直接从Entity Framework执行,如下所示:

db.Database.ExecuteSqlCommand( <your SQL statement here> );