You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Entity Framework Core与ASP.NET Core MVC中外键使用问题求助

问题解答:外键读写错误已修复,现求助分页数据视图展示

更新说明

部分问题已解决,感谢各位帮助,创建功能已修复。目前编写了如下分页查询代码,但不知如何在视图中展示数据:

public IEnumerable<object> Paging(int page)
{
    int t = (page - 1) * 10;
    DB db = new DB();

    //var q = db.Books.Skip(t).Take(10).ToList();

    var q = (from i in db.Books
             select new
             {
                 i.id,
                 i.BookName,
                 i.Writer,
                 i.BookcategFK.BookCategori,
                 i.inventory,
                 i.BannerImage,
                 
             }
             ).Skip(t).Take(10).ToList();

    return q;
}

原问题(已解决)

此前创建book和type表并定义外键后,读写外键列时出现错误,相关代码如下:

控制器代码

UploadFile UP = new UploadFile(Environment);

Book B = new Book();

BLBook BLB = new BLBook();

B.BookName = MBM.BookName;
B.BookcategFK.id = MBM.BookcategFK; // 此处报错
B.CoverType = MBM.CoverType;
B.PublishedNumber = MBM.PublishedNumber;
B.BannerImage = UP.uploadBook(MBM.BannerImage);
        
B.Atleast = MBM.Atleast;
B.inventory = MBM.inventory;
B.Price = MBM.Price;
B.Discount = MBM.Discount;

BLB.Create(B,MBM.BookcategFK); 
        
return View("BookCreate");

视图标记

<div class="form-group">
    <label for="dropdownrole">دسته بندی :</label>
    <div class="custom-control custom-radio xmt-3">
        <select class="custom-select mt-3" id="BookcategFK" name="BookcategFK">
            @{
                if (!Model.Any())
                {

                }
                else
                {
                    foreach (var item in Model)
                    {
                        <option value="@item.id">@item.BookCategori</option> // 此处报错
                    }
                }
            }
        </select>
    </div>
    <div class="valid-feedback">acepte</div>
    <div class="invalid-feedback">fill it please</div>
</div>

模型代码

namespace Online_Book_Shop.Models
{
public class BookModel
{
    public int id { get; set; }

    public bool DS { get; set; }

    public string BookName { get; set; }

    public int BookcategFK { get; set; }

    
    public string Publisher { get; set; }
}

业务实体类代码

public class Book
{
    public int id { get; set; }

    public bool DS { get; set; }
    public string BookName { get; set; }

    public BookCategorization BookcategFK { get; set; }
    public string Publisher { get; set; }
 }

分页数据视图展示解决方案

1. 替换匿名类型为强类型视图模型

匿名类型无法在视图中直接使用强类型访问,建议创建专用的视图模型:

namespace Online_Book_Shop.Models
{
    public class BookListItemViewModel
    {
        public int id { get; set; }
        public string BookName { get; set; }
        public string Writer { get; set; }
        public string BookCategori { get; set; }
        public int inventory { get; set; }
        public string BannerImage { get; set; }
    }
}

2. 修改分页方法返回强类型

同时优化数据库连接的资源释放:

public IEnumerable<BookListItemViewModel> Paging(int page)
{
    int skipCount = (page - 1) * 10;
    using (DB db = new DB()) // 使用using自动释放数据库连接
    {
        return db.Books
                 .Select(book => new BookListItemViewModel
                 {
                     id = book.id,
                     BookName = book.BookName,
                     Writer = book.Writer,
                     BookCategori = book.BookcategFK.BookCategori,
                     inventory = book.inventory,
                     BannerImage = book.BannerImage
                 })
                 .Skip(skipCount)
                 .Take(10)
                 .ToList();
    }
}

3. 控制器传递数据到视图

在控制器动作中调用分页方法,将数据传入视图:

public IActionResult BookList(int page = 1)
{
    BLBook blBook = new BLBook();
    var bookList = blBook.Paging(page);
    return View(bookList);
}

4. 创建强类型视图展示数据

创建对应BookList动作的视图,使用强类型模型遍历展示数据,并添加分页导航:

@model IEnumerable<Online_Book_Shop.Models.BookListItemViewModel>

<h2>书籍列表</h2>

<table class="table table-bordered">
    <thead>
        <tr>
            <th>ID</th>
            <th>书名</th>
            <th>作者</th>
            <th>分类</th>
            <th>库存</th>
            <th>封面</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var book in Model)
        {
            <tr>
                <td>@book.id</td>
                <td>@book.BookName</td>
                <td>@book.Writer</td>
                <td>@book.BookCategori</td>
                <td>@book.inventory</td>
                <td>
                    @if (!string.IsNullOrWhiteSpace(book.BannerImage))
                    {
                        <img src="@Url.Content(book.BannerImage)" alt="@book.BookName" style="width:80px; height:auto;" />
                    }
                    else
                    {
                        <span class="text-muted">无封面</span>
                    }
                </td>
            </tr>
        }
    </tbody>
</table>

<!-- 分页导航区域 -->
<div class="mt-3">
    @{
        int currentPage = int.TryParse(Request.Query["page"], out int pageNum) ? pageNum : 1;
    }
    <a href="@Url.Action("BookList", new { page = currentPage - 1 })" class="btn btn-sm btn-outline-primary @(currentPage <= 1 ? "disabled" : "")">上一页</a>
    <span class="mx-2">第 @currentPage 页</span>
    <a href="@Url.Action("BookList", new { page = currentPage + 1 })" class="btn btn-sm btn-outline-primary">下一页</a>
</div>

内容的提问来源于stack exchange,提问作者link

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:20:42