gpt4 book ai didi

c# - 将 linq 转换为模型类失败 "Unable to cast object of type ' System.Data.Entity.Infrastruct.DbQuery`1"

转载 作者:行者123 更新时间:2023-12-02 21:19:10 24 4
gpt4 key购买 nike

我正在尝试从下面的 Controller 将模型返回到我的 View 。

JobPost model = (JobPost)
(from posts in repository.JobPosts
orderby posts.PostDate descending
select new
{
Id = posts.Id,
Post = posts.Post,
Logo = posts.Logo,
PostDate = posts.PostDate,
Employer = posts.Employer,
Region = posts.Region,
JobType = posts.JobType,
PostTitle = posts.PostTitle,
Industry = posts.Industry,
JobFunction = posts.JobFunction,
JobLevel = posts.JobLevel,
Salary = posts.Salary,
Experience = posts.Experience
}).Select(x => new JobPost
{
Id = x.Id,
Post = x.Post,
Logo = x.Logo,
PostDate = x.PostDate,
Employer = x.Employer,
Region = x.Region,
JobType = x.JobType,
PostTitle = x.PostTitle,
Industry = x.Industry,
JobFunction = x.JobFunction,
JobLevel = x.JobLevel,
Salary = x.Salary,
Experience = x.Experience
});

return View(model);

我的 View 接收 JobPost 类型的模型。下面是 jobPost 类

public class JobPost
{
public long Id { get; set; }
public string Post { get; set; }
public string Logo { get; set; }
public DateTime PostDate { get; set; }
public string Employer { get; set; }
public string Region { get; set; }
public string JobType { get; set; }
public string PostTitle { get; set; }
public string Industry { get; set; }
public string JobFunction { get; set; }
public string JobLevel { get; set; }
public decimal Salary { get; set; }
public int Experience { get; set; }
}

我该如何正确地转换它?当我说 select new 时,这不会将类型更改为匿名而不是 DbQuery 吗?错误内容为

"Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1".

最佳答案

只需像下面这样的简单查询就可以工作。

JobPost model = (from post in repository.JobPosts
orderby post.PostDate descending
select post).FirstOrDefault();

我认为没有必要创建 Jobpost 的新实例并设置所有属性。

关于c# - 将 linq 转换为模型类失败 "Unable to cast object of type ' System.Data.Entity.Infrastruct.DbQuery`1",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28625190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com