c# - 如何编写 linq 查询来获取 mvc Web 应用程序中的 blogId

标签 c# mysql asp.net-mvc linq

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

相关文章:

mysql - 如何在不编写脚本的情况下在MySql中模拟死锁?

php - jQuery/AJAX 检索新插入记录的 ID 并在页面刷新之前在 HTML 中使用它

asp.net-mvc - asp.net mvc - string 或 int 的路由(即/type/23 或/type/hats)

c# - 检测游戏是否在安卓模拟器中运行

c# - 是否有访问 C++ native COM 函数以从 C# 互操作的最佳实践?

c# - MVC Bootstrap typeahead HtmlHelper

mysql - 使用左连接语法 SQL

c# - asp.net mvc 自定义属性中的执行优先级

javascript - 对通过 Javascript 写入屏幕的 Html 帮助程序进行编码

c# - Razor MVC 3 中变量的范围是什么