EntityFramework生成的奇怪SQL查询

时间:2014-03-26 23:20:24

标签: c# asp.net sql sql-server entity-framework

这是我的EF生成的SQL查询。

The thread '<No Name>' (0x1884) has exited with code 0 (0x0).
Opened connection at 26-Mar-14 23:39:33 +01:00
Opened connection at 26-Mar-14 23:39:35 +01:00
Started transaction at 26-Mar-14 23:39:35 +01:00
Started transaction at 26-Mar-14 23:39:35 +01:00
INSERT [dbo].[Tagger]([tagCount], [imageId], [tag])
VALUES (@0, @1, @2)
SELECT [id]
FROM [dbo].[Tagger]
WHERE @@ROWCOUNT > 0 AND [id] = scope_identity()
-- @0: '1' (Type = Int32)
-- @1: '1' (Type = Int32)
-- @2: 'tag1' (Type = String, Size = -1)
-- Executing at 26-Mar-14 23:39:35 +01:00
INSERT [dbo].[Tagger]([tagCount], [imageId], [tag])
VALUES (@0, @1, @2)
SELECT [id]
FROM [dbo].[Tagger]
WHERE @@ROWCOUNT > 0 AND [id] = scope_identity()
-- @0: '1' (Type = Int32)
-- @1: '1' (Type = Int32)
-- Completed in 3 ms with result: SqlDataReader

-- @2: 'tag1' (Type = String, Size = -1)
-- Executing at 26-Mar-14 23:39:35 +01:00
-- Completed in 0 ms with result: SqlDataReader

Committed transaction at 26-Mar-14 23:39:35 +01:00
Committed transaction at 26-Mar-14 23:39:35 +01:00
Closed connection at 26-Mar-14 23:39:35 +01:00
Closed connection at 26-Mar-14 23:39:35 +01:00 

我认为这很奇怪,因为我在控制器中的代码看起来像这样

private void addTagsToTagger(FormCollection form)
{

    char[] delimiter = { ',' };
    List<string> userTags = form["tags"].Split(delimiter).ToList();


    using (var ctx = new vestibulyContext())
    {
        ctx.Database.Log = s => log(s);
        foreach (var tagItem in userTags)
        {
            if (!IssetTagInDb(ctx, tagItem))
            {
                var item = tagItem.ToLower().Trim();
                var t = new Tagger() { imageId = Int16.Parse(form["imgId"]), tag = item, tagCount = 1 };
                ctx.Tagger.Add(t);
                ctx.SaveChanges();
            }
        }
    }

}

private bool IssetTagInDb(vestibulyContext ctx, string tag)
{
    tag = tag.ToLower().Trim();
    return ctx.Tagger.Any(t => t.tag == tag); 
}

所以,在foreach循环的每一步中我调用SaveChanges()方法,我不知道为什么EF生成这样的查询。开头是2行打开连接。为什么?之后2次启动事务,之后进行2次INSERT查询。这是正常的行为吗?我无法想象当我在每一步使用1次Add()方法和1次SaveChanges()方法后,为什么有2次插入查询。因此我的记录被添加到数据库中2次。知道这有什么问题吗?谢谢。

0 个答案:

没有答案