实体框架协会绩效

时间:2011-01-21 21:34:25

标签: entity-framework entity-framework-4

我有以下关联.GroupFile与MappedFolders有一对多的关系(通过MappedFolder导航属性)。

alt text

我希望下一行能够进行更新:

groupFile.MappedFolder = _mappedFoldersRepository.Query(m => m.FolderName == "Unassigned").FirstOrDefault();

Query(根据分析器)正在执行此SQL:

SELECT TOP ( 1 ) [Extent1].[MappedFolderId] AS [MappedFolderId],
                 [Extent1].[FolderPath]     AS [FolderPath],
                 [Extent1].[FolderName]     AS [FolderName],
                 [Extent1].[HotFolder]      AS [HotFolder],
                 [Extent1].[Workstation]    AS [Workstation]
FROM   [dbo].[MappedFolders] AS [Extent1]
WHERE  N'Unassigned' = [Extent1].[FolderName]

但根据Entity Framework Profiler,赋值本身在开始事务之前执行此SQL语句:

SELECT [Extent1].[Id]                          AS [Id],
       [Extent1].[Path]                        AS [Path],
       [Extent1].[Status]                      AS [Status],
       [Extent1].[DateAdded]                   AS [DateAdded],
       [Extent1].[DateLastUpdated]             AS [DateLastUpdated],
       [Extent1].[JobSetup_SetupId]            AS [JobSetup_SetupId],
       [Extent1].[Group_GroupId]               AS [Group_GroupId],
       [Extent1].[MappedFolder_MappedFolderId] AS [MappedFolder_MappedFolderId]
FROM   [dbo].[GroupFiles] AS [Extent1]
WHERE  [Extent1].[MappedFolder_MappedFolderId] = 7 /* @EntityKeyValue1 */

我必须遗漏一些微妙的东西(或者不那么微妙),但我不确定为什么需要SQL语句.... 更新: 进一步了解分析器告诉我的内容,SQL语句与以下内容相关联:

public virtual MappedFolders MappedFolder
{
    get { return _mappedFolder; }
    set
    {
        if (!ReferenceEquals(_mappedFolder, value))
        {
            var previousValue = _mappedFolder;
            _mappedFolder = value;
            FixupMappedFolder(previousValue);
        }
    }
}


private void FixupMappedFolder(MappedFolders previousValue)
{
    if (previousValue != null && previousValue.GroupFiles.Contains(this))
    {
        previousValue.GroupFiles.Remove(this);
    }

    if (MappedFolder != null)
    {   
        // THIS IS WHAT THE SQL STATEMENT IS FOR!!!!!
        if (!MappedFolder.GroupFiles.Contains(this))
        {
            MappedFolder.GroupFiles.Add(this);
        }
    }
}

生成的代码正在检查映射文件夹的GroupFiles集合以查看它是否已被添加?

1 个答案:

答案 0 :(得分:0)

您将看到用于检索与此关联的实体的select语句:

_mappedFoldersRepository.Query(m => m.FolderName == "Unassigned").FirstOrDefault();

在致电groupFile.MappedFolder之前,ObjectContext.SaveChanges的分配不会更新数据库。此时您应该看到更新语句。