首先通过Entity Framework 6代码仅从数据库表中加载ID

时间:2013-11-19 18:07:30

标签: c# entity-framework

我有实体User with properties

int Id {get; set;}

设置为主键

和财产

   virtual List<Right> Rights {get; set;}

是一个属性保存用户权限列表,并在需要时延迟加载。

右也是财产:

public class Right
    {
        [Key]
        public int Id {get; set;}

        public RightType RightType { get; set; }
    }

 public enum RightType : byte
    {
        Own,
        Copy,
        Delete
    }

在我的代码中,我像往常一样从数据库创建用户,后来我想只获取权限的ID,所以我这样试试:

myUser.Rights.Select(x=>x.Id).ToList();

它为我提供了我想要的ID集合,但是访问数据库的查询获取了权限表的所有列,这些列并不是必需的,而在其他情况下,它可能非常有问题(想象只将大量数据加载到获取ID:/)

查询如下:

> "SELECT 
>     [Extent1].[Id] AS [Id], 
>     [Extent1].[RightType] AS [RightType], 
>     [Extent1].[User_Id] AS [User_Id]
>     FROM [dbo].[Rights] AS [Extent1]
>     WHERE ([Extent1].[User_Id] IS NOT NULL) AND ([Extent1].[User_Id] = @EntityKeyValue1)"

你知道怎么只加载ID吗? 任何帮助将不胜感激:)

谢谢

1 个答案:

答案 0 :(得分:1)

你可以试试这样的事情:

    var ids = _context
.Set<User>()
.Where(u.Id==id)
.SelectMany(u=>u.Rights.Select(r=>r.Id))
.ToList();

不要尝试对抗EF,但是如果进行了一些接口,那么下面的泛型和LINQ应该可以工作:

        public interface IHaveId<T>
        {
            T Id { get; set; }
        }

        public class User : IHaveId<int>
        {
            public int Id { get; set; }
            public virtual List<Right> Rights { get; set; }
        }

        public class Right : IHaveId<int>
        {
            public int Id { get; set; }

            public RightType RightType { get; set; }
        }

        public enum RightType : byte
        {
            Own,
            Copy,
            Delete
        }

        public static IEnumerable<TKey> GetChildIds<TParent,TChild,TKey>(IQueryable<TParent> src, TKey parentId, Expression<Func<TParent,IEnumerable<TChild>>> childSelector)
            where TParent : IHaveId<TKey>
            where TChild : IHaveId<TKey>
            where TKey : struct, IEquatable<TKey>

        {
            var result = src
                .Where(parent => parentId.Equals(parent.Id))
                .SelectMany(childSelector)
                .Select(child => child.Id);

            return result;
        }
//sample usage
//var ids = GetChildIds<User,Right,int>(_context.DbSet<User>(), user=>user.Rights).ToList();