无法使用Entities将IEnumerable类型隐式转换为IQueryable

时间:2014-06-19 10:22:13

标签: c# asp.net linq

我对实体完全不熟悉(我已经接管了另一个人项目),因此我很遗憾地忽略了一些关键事实,但我会尝试解释我的问题:

我的申请人有一个表格,上面有他们的信息,如名字等。我还有一个表格与ASP.NET用户。这些表由user_id链接。

我试图在下拉列表中将登录名设置为可选择的列表项,但为了这样做,我需要加入这两个表。我写了以下代码:

var container = new ModelContainer();
var manager = new ApplicantDBManager();

IEnumerable<Business.Entities.EF.Applicant> applicantQuery;

if (txtSearch.Text.Equals(string.Empty))
{
    applicantQuery = container.Applicants;
}
else
{
    var ids = manager.ApplicantSearchForIDs(ddlSearch.SelectedValue, txtSearch.Text, chkIncludeInactive.Checked);

    applicantQuery = (from a in container.Applicants
                      join u in container.Users on a.user_id equals u.user_id
                      where ids.Contains(a.user_id)
                      select new
                      {
                          user_id = a.user_id,
                          first_name = a.first_name,
                          last_name = a.last_name,
                          login_name = u.login_name,
                          date_of_birth = a.date_of_birth,
                          kot_cpr = a.kot_cpr,
                          address = a.address,
                          email = a.email,
                          telephone_number = a.telephone_number,
                          citizenship = a.citizenship
                      });
}

我收到类似&#34的错误;无法将类型System.Linq.Iqueryable隐式转换为System.Collections.Generic.IEnumerable&#34;似乎并不重要我如何尝试和修复它(我已经尝试添加.ToList()。AsQueryable(),First()等没有运气)。我认为这与申请人实体有关吗?

3 个答案:

答案 0 :(得分:5)

这是问题所在:

select new 
{
    ...
}

这是创建一个匿名类型的实例。您希望如何创建Business.Entities.EF.Applicant对象?

您可能只是需要将代码更改为:

select new Business.Entities.EF.Applicant
{
    ...
}

答案 1 :(得分:0)

您需要更改代码。将代码更改为

select new Business.Entities.EF.Applicant
{
user_id = a.user_id,
first_name = a.first_name,
last_name = a.last_name,
login_name = u.login_name,
date_of_birth = a.date_of_birth,
kot_cpr = a.kot_cpr,
address = a.address,
email = a.email,
telephone_number = a.telephone_number,
citizenship = a.citizenship
}

答案 2 :(得分:0)

select new返回匿名类型对象,而applicantQuery的类型为Business.Entities.EF.Applicant。因此,像Jon Skeet所说,返回预期类型的​​对象。