在LINQ to Entities中选择多列时出现无效的匿名类型错误
本文关键字:无效 错误 类型 Entities to LINQ 选择 | 更新日期: 2023-09-27 18:24:43
我正试图从几个不同的LINQ查询填充我的ViewModel
,但我遇到了从一个LINQ查询中填充多个属性的问题,但我得到了错误
无效的匿名类型成员声明符。匿名类型成员必须用成员分配、简单名称或成员访问声明
我做了一些搜索,找到了一些帖子,但它们都是关于完全填充ViewModel
,而不仅仅是像我试图做的一些属性。我应该怎么做才能解决这个问题,还是我完全错了?
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();
}
我的型号:
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; }
}
不能在匿名类型声明中分配变量。您需要首先选择匿名类型变量,并将其属性逐一分配给模型属性。更改此部件
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();
到这个
var poll = db.yaf_Poll
.Where(p => p.PollID == model.ID)
.Select(p => new
{
p.Question,
p.AllowMultipleChoices,
p.Closes
})
.First();
model.Question = poll.Question;
model.IsMultipleChocie = poll.AllowMultipleChoices;
model.ExperationDate = poll.Closes;
下面的第三个查询有相同的问题
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();
我想可能有不止一种选择,所以把你的型号改为
public class PollVM
{
public PollVM()
{
this.Choices = new List<KeyValuePair<string, int>>();
}
public int ID { get; set; }
public string Question { get; set; }
public bool IsMultipleChocie { get; set; }
public DateTime? ExperationDate { get; set; }
public List<KeyValuePair<string, int>> Choices { get; set; }
public List<string> VotedIPs { get; set; }
public List<int?> VotedUserIDs { get; set; }
}
并将第三个查询更改为该
var choices = db.yaf_Choice
.Where(c => c.PollID == model.ID)
.Select(c => new
{
c.Choice,
c.Votes,
})
.ToList();
foreach (var ch in choices)
{
model.Choices.Add(new KeyValuePair<string, int>(ch.Choice, ch.Votes));
}