【问题标题】:Return view of a list from EF mapped class in ASP.NET MVC Core从 ASP.NET MVC Core 中的 EF 映射类返回列表视图
【发布时间】:2017-03-10 18:21:29
【问题描述】:

我将 ASP.NET MVC Core 与 EF 1.1.0 和 LocalDB 一起使用,并尝试搜索博客 ID(从 url GET 提供),然后发送以查看博客的帖子列表。

大部分代码取自 microsoft docs 示例。

数据库上下文:

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
        : base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

控制器:

public class BlogsController : Controller
{
    private readonly BloggingContext _context;

    public BlogsController(BloggingContext context)
    {
        _context = context;    
    }

    // GET: Blogs/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var blog = await _context.Blogs
            .SingleOrDefaultAsync(m => m.BlogId == id);
        if (blog == null)
        {
            return NotFound();
        }

        return View(blog.Posts); // HERE IS PROBABLY THE PROBLEM
    }
}

查看:

@model IEnumerable<EFGetStarted.AspNetCore.NewDb.Models.Post>

<h2>Details</h2>

<table>

@foreach (var item in Model) {
    <tr>
        <td>
            @item.Title
        </td>
    </tr>
}

</table>

我得到一张空桌子..谁能帮忙?

谢谢。

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-core asp.net-core-mvc


    【解决方案1】:

    您需要使用 Include 来确保您的查询拉入博客的相关帖子。

     var blog = await _context.Blogs
                .SingleOrDefaultAsync(m => m.BlogId == id);
    

    必须改为

    var blog = await _context.Blogs.Include("Posts")
                .SingleOrDefaultAsync(m => m.BlogId == id);
    

    【讨论】:

    • 谢谢!这样可行。 Include("Posts") 部分需要在 Blogs 之后而不是在末尾。
    • 一般正确,但Include 应该在.SingleOrDefault 之前。
    猜你喜欢
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 2017-01-19
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2020-06-16
    相关资源
    最近更新 更多