简体   繁体   English

为什么此linq投影不起作用?

[英]Why does this linq projection not work?

The version commented out does not work for some reason ? 由于某些原因,注释掉的版本不起作用? What I want to do is strip out the fields that I do not need in the UI.. Is this the proper way to do it ? 我想做的是去掉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;
    }

EDIT 1: It compiles fine both ways. 编辑1:两种方式都可以编译。 With just the select m it compiles and runs fine. 仅使用select m即可编译并正常运行。 With the other line when it gets to the foreach it says 与另一行谈到foreach时说

An exception of type 'System.NotSupportedException' occurred in mscorlib.dll but was not handled in user code mscorlib.dll中发生类型'System.NotSupportedException'的异常,但未在用户代码中处理

Additional information: The entity or complex type 'CongressDb_DevModel.tMember' cannot be constructed in a LINQ to Entities query. 附加信息:实体或复杂类型'CongressDb_DevModel.tMember'不能在LINQ to Entities查询中构造。

EDIT2: the constructor is 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>();
    }

Just create a new type, rather than trying to reuse tMember . 只需创建一个新类型,而不要尝试重用tMember

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

Then change the return type of the method and change the select to: 然后更改方法的返回类型,并将选择更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM