我有 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/