[RESOLVED]LINQ to Entities, selecting mutiple columns to already declared model getting anonymous type error.

I am trying to fill my `ViewModel` from a few different LINQ queries but I am running into the problem of trying to fill multiple properties from a single LINQ query but I get the error

"invalid anonymous type member declarator. anonymous type members must be declared with a member assignment, simple name or member access"

I have done some searches and founds some posts but they are all about completely filling a `ViewModel` and not just a few properties like I am trying to do. What am I supposed to do to fix this, or am I going about this completely wrong?

using (ForumContext db = new ForumContext())
{
	model.ID = db.yaf_Topic
				.Where(t => t.ForumID == 5)
				.OrderByDescending(t => t.Posted)
				.Select(t => t.PollID.Value).First();

	model = db.yaf_Poll
				.Where(p => p.PollID == model.ID)
				.Select(p => new
				{
					model.Question = p.Question,
					model.IsMultipleChocie = p.AllowMultipleChoices,
					model.ExperationDate = p.Closes
				})
				.First();

	model.Choices = db.yaf_Choice
						.Where(c => c.PollID == model.ID)
						.Select(c => new
						{
							model.Votes.Key = c.Choice,
							model.Votes.Value = c.Votes,
						})
						.ToList();

	model.VotedIPs = db.yaf_PollVote
						.Where(p => p.PollID == model.ID)
						.Select(p => p.RemoteIP)
						.ToList();

	model.VotedUserIDs = db.yaf_PollVote
							.Where(p => p.PollID == model.ID)
							.Select(p => p.UserID)
							.ToList();
}

ViewModel:

public class PollVM
{
	public int ID { get; set; }
	public string Question { get; set; }
	public bool IsMultipleChocie { get; set; }
	public DateTime? ExperationDate { get; set; }
	public KeyValuePair<string, int> Choices { get; set; }
	public List<string> VotedIPs { get; set; }
	public List<int?> VotedUserIDs { get; set; }
}

Here are the issues, I observe in your code

Eagle_f90

.Select(c => new

You are using anonymous type and hence you are getting the error, you need to specify the datatype as below

	model.Choices = db.yaf_Choice
						.Where(c => c.PollID == model.ID)
						.Select new KeyValuePair<string, int>(c.Choice, c.Votes)
						})
						.ToList();

You should make your Choices to be a list of keyvaluepair

public List<KeyValuePair<string, int>> Choices { get; set; }


Eagle_f90

model = db.yaf_Poll		
.Where(p => p.PollID == model.ID) .Select(p => new { model.Question = p.Question, model.IsMultipleChocie = p.AllowMultipleChoices, model.ExperationDate = p.Closes }) .First();

With this step you are overriding your previous step of setting Model.ID. Also you need to change the "new" to something like I mentioned above.

Leave a Reply