简体   繁体   中英

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 ?

   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. With just the select m it compiles and runs fine. With the other line when it gets to the foreach it says

An exception of type 'System.NotSupportedException' occurred in mscorlib.dll but was not handled in user code

Additional information: The entity or complex type 'CongressDb_DevModel.tMember' cannot be constructed in a LINQ to Entities query.

EDIT2: the constructor is

   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 .

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 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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