从ASP.NET MVC Core中的EF映射类返回列表视图

时间:2017-03-10 18:21:30

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

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

大部分代码都来自microsoft docs examples。

数据库上下文:

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>

我得到一张空桌......任何人都可以帮忙吗?

感谢。

1 个答案:

答案 0 :(得分:2)

您需要使用Include确保您的查询提取博客的相关帖子。

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

必须更改为

android:layout_width="match_parent"
android:layout_height="fill_parent"
android:background="@color/listColor"
android:layout_weight="1"
android:orientation="vertical"

>

    <TextView


        android:layout_width="match_parent"
        android:layout_height="fill_parent"

        android:layout_weight="1"

        android:background="@drawable/layout_item_value"

        android:text="163,00"

        android:textSize="18.2dp"

        android:gravity="center_vertical|center_horizontal"

        android:id="@+id/txtListValue"
        android:textColor="@color/back"



        />


    <ImageView
        android:id="@+id/image_order"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_weight="1"
        android:scaleX="0.4"
        android:scaleY="0.4"
        android:gravity="center_vertical|center_horizontal"

        />
相关问题