gpt4 book ai didi

c# - 如何编写 linq 查询以在 mvc web 应用程序中获取 blogId

转载 作者:行者123 更新时间:2023-11-29 01:37:57 24 4
gpt4 key购买 nike

我有 2 个模型:

public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string RealBlogId { get; set; }
}

public class Post
{
public int Id { get; set; }
public int? BlogId { get; set; }
public string Title { get; set; }
public int? ReadingNumber { get; set; }
public string RealPostId { get; set; }
public string Url { get; set; }
public string Category { get; set; }
public DateTime PublishedTime { get; set; }
}

我想在 PostController 中编写一个返回我 RealBlogId 的函数使用 postId

 public class PostController : Controller
{
private ReaderDb db = new ReaderDb();

public ActionResult Details(int? postId)
{
if (postId == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Post post = db.Posts.Find(postId);
if (post == null)
{
return HttpNotFound();
}
IQueryable<string>realPostId = from r in db.Posts
where r.Id == id //This query gives me realPostId
select r.RealId;

//second query

}

我如何编写一个在第二个查询中返回 realBlogId 的查询

最佳答案

这是一种方法:

var query = from post in db.Posts
from blog in db.Blogs
where post.BlogId == blog.Id && post.Id == postId
select blog.RealBlogId;

var result = query.FirstOrDefault();

更好的方法是修改模型,使它们之间的关系明确如下:

public class Blog
{
public Blog()
{
Posts = new HashSet<Post>();
}

public int Id { get; set; }
public virtual ICollection<Post> Posts { get; set; }

//Rest of properties here
}

public class Post
{
public int Id { get; set; }

public int? BlogId { get; set; }
public virtual Blog Blog { get; set; }
//Reset of properties here

}

这将允许您创建这样的查询:

var result = db.Posts
.Where(x => x.Id == postId)
.Select(x => x.Blog.RealBlogId) //Notice how we reference Post.Blog here
.FirstOrDefault();

关于c# - 如何编写 linq 查询以在 mvc web 应用程序中获取 blogId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34561304/

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