return list with anonymous type in entity framework

后端 未结 6 1495
北恋
北恋 2021-01-02 07:21

How i can return list with anonymous type, because with this code i get

\"The type or namespace name \'T\' could not be found (are you missing a using directive or a

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 08:03

    You can return anonymous types by casting them to Object, but this is rarely useful. However if you are returning it from say an WebApi controller as a quick and (not so) dirty DTO then I think it is perfectly fine. This only works with JSON though. XML will complain about the schema or something, but nowadays everybody use JSON anyway :)

    public static List GetMembersItems(string ProjectGuid)
    {
        using (PMEntities context = new PMEntities("name=PMEntities"))
        {
            var items = context.Knowledge_Project_Members.Include("Knowledge_Project").Include("Profile_Information")
                        .Where(p => p.Knowledge_Project.Guid == ProjectGuid)
                        .Select(row => new { IdMember = row.IdMember, UserName = row.Profile_Information.UserName });
    
            return items
                   .ToList() // this is only needed to make EF happy otherwise it complains about the cast
                   .Cast()
                   .ToList();
        }
    }
    
        

    提交回复
    热议问题