为什么这个linq投影不起作用?

时间:2013-11-15 19:55:08

标签: c# json linq

由于某些原因,注释掉的版本不起作用?我想要做的是删除UI中不需要的字段。这是正确的方法吗?

   public IQueryable<tMember> Get(int id)
    {


        var congressGroup = from m in db.tMembers
                            join mp in db.tMemPositions on m.MembersID equals mp.MembersID
                            join cmp in db.tCongressMemPositions on mp.MemPositionsID equals cmp.MemPositionsID
                            join c in db.tCongresses on cmp.CongressID equals c.CongressID
                            where c.CongressNumber == id
                            //  select new tMember { Firstname = m.Firstname, Lastname = m.Lastname };
                            select m;

        //testing
        foreach (tMember m in congressGroup)
        {


        }


        return congressGroup;
    }

编辑1:它编写两种方式都很好。只需选择m,它就可以编译并运行正常。当它到达foreach时,另一条线就是

mscorlib.dll中发生了'System.NotSupportedException'类型的异常,但未在用户代码中处理

附加信息:无法在LINQ to Entities查询中构造实体或复杂类型“CongressDb_DevModel.tMember”。

EDIT2:构造函数是

   public tMember()
    {
        this.tMemMilitaries = new HashSet<tMemMilitary>();
        this.tMemOccupations = new HashSet<tMemOccupation>();
        this.tMemPositions = new HashSet<tMemPosition>();
        this.tMemRatings = new HashSet<tMemRating>();
        this.tMemVoteScores = new HashSet<tMemVoteScore>();
    }

1 个答案:

答案 0 :(得分:2)

只需创建一个新类型,而不是尝试重用tMember

public class Name
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

然后更改方法的返回类型并将选择更改为:

select new Name { Firstname = m.Firstname, Lastname = m.Lastname };