如何在mvc web应用程序中编写linq查询来获取blogId
本文关键字:linq 查询 blogId 获取 mvc web 应用程序 | 更新日期: 2023-09-27 18:28:37
我有两种型号:
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();
您可以使用此LINQ查询来完成此操作
var realBlogId = (from post in db.Posts
join blog in db.Blogs on post.BlogId equals blog.Id
where post.Id == postId
select blog.RealBlogId)
.FirstOrDefault();
或者使用lambda
var realBlogId = db.Posts.Where(p => p.Id == postId)
.Join(db.Blogs, p => p.BlogId, b => b.Id, (p, b) => b.RealBlogId)
.FirstOrDefault();
下面的代码应该有效。
db.Blogs.Where(blog =>
db.Posts.Where(post => post.Id == postId)
.Any(post => post.BlogId == blog.Id));
我们选择每个博客都被任何具有特定id的帖子引用。