在投射到类时,EntityFramework会向查询添加列

时间:2015-06-26 14:25:48

标签: entity-framework

我发现在选择要检索的一堆列时,EF会包含额外的Id列,但在选择单个列时不会这样做:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;

class User
{
    public int UserId { get; set; }
    public int GroupId { get; set; }
    public Group Group { get; set; }
    [Required]
    public string UserName { get; set; }
}
class Group
{
    public int GroupId { get; set; }
    [Required]
    public string GroupName { get; set; }
    public ICollection<Rule> Rules { get; set; }
    public ICollection<User> Users { get; set; }
}
class Rule
{
    public int RuleId { get; set; }
    public int GroupId { get; set; }
    public Group Group { get; set; }
    [Required]
    public string RuleName { get; set; }
}
class EFExtraCol : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Group> Groups { get; set; }
    public DbSet<Rule> Rules { get; set; }
    static void Main()
    {
        var db = new EFExtraCol();

        //SELECT
        //    [Extent1].[GroupId] AS [GroupId],
        //    [Extent2].[RuleName] AS [RuleName]
        //    FROM  [dbo].[Users] AS [Extent1]
        //    INNER JOIN [dbo].[Rules] AS [Extent2] ON [Extent1].[GroupId] = [Extent2].[GroupId]
        //    WHERE N'' = [Extent1].[UserName]
        Console.WriteLine(
            db.Users
            .Where(u => u.UserName == "")
            .SelectMany(u => u.Group.Rules)
            .Select(r => new { r.RuleName, })
            .ToString());

        //SELECT
        //    [Extent2].[RuleName] AS [RuleName]
        //    FROM  [dbo].[Users] AS [Extent1]
        //    INNER JOIN [dbo].[Rules] AS [Extent2] ON [Extent1].[GroupId] = [Extent2].[GroupId]
        //    WHERE N'' = [Extent1].[UserName]
        Console.WriteLine(
            db.Users
            .Where(u => u.UserName == "")
            .SelectMany(u => u.Group.Rules)
            .Select(r => r.RuleName)
            .ToString());

        //SELECT
        //    [Extent1].[UserId] AS [UserId],
        //    [Extent2].[RuleName] AS [RuleName]
        //    FROM  [dbo].[Users] AS [Extent1]
        //    INNER JOIN [dbo].[Rules] AS [Extent2] ON [Extent1].[GroupId] = [Extent2].[GroupId]
        //    WHERE 0 = [Extent1].[UserId]
        Console.WriteLine(
            db.Users
            .Where(u => u.UserId == 0)
            .SelectMany(u => u.Group.Rules)
            .Select(r => new { r.RuleName, })
            .ToString());
    }
}

请注意,第一个查询包含GroupId,但第三个查询包含UserId。为什么是这样?这是一个错误吗?我认为可能包括id强制SqlServer包含每个规则,即使名称相同,但Id列中的更改没有意义。

更新:我提交了https://entityframework.codeplex.com/workitem/2773

0 个答案:

没有答案