ASP.NET Core Web API 和具有外键关系的 EF Core 模型

ASP.NET Core Web API & EF Core Models with Foreign Key relationship

我正在开发一个用于教育目的的基本 Web API 项目,但我在处理 EF 模型关系时遇到了问题。我有 2 个模型。 MessageMessageBoard.

public class Message
    {
        public long Id { get; set; }
        public string Text { get; set; }
        public string User { get; set; }
        public DateTime PostedDate { get; set; }

        public long MessageBoardId { get; set; }
        [ForeignKey("MessageBoardId")]
        public MessageBoard MessageBoard { get; set; }
    }

public class MessageBoard
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public ICollection<Message> Messages { get; set; }
    }

我已经设置了我的 DBContext 并创建了一个迁移来配置数据库。我使用 EF 脚手架生成了两个 Web API 控制器。迁移似乎正确地检测了两个模型之间的关系:

modelBuilder.Entity("Asp.net_Core_Web_Api.Models.Message", b =>
{
   b.HasOne("Asp.net_Core_Web_Api.Models.MessageBoard", "MessageBoard")
   .WithMany("Messages")
   .HasForeignKey("MessageBoardId")
   .OnDelete(DeleteBehavior.Cascade);
});

但是,当我创建一个 MessageBoard,然后使用 MessageBoard 的 ID 创建一条消息时,它们似乎 link 不正确。在 PostMan 中,我正在执行以下操作:

1) Post 一个新的留言板

POST - https://localhost:44384/api/MessageBoards/

Body - Raw - Json

{
 "Name":"Test Board",
 "Description":"A Message board for testing purposes."
}

Returns

{
    "id": 4,
    "name": "Test Board",
    "description": "A Message board for testing purposes.",
    "messages": null
}

2) Post 一条新消息

POST - https://localhost:44384/api/Messages

Body - Raw - JSON

{
    "Text":"Posting my first message!",
    "User":"Jesse",
    "PostedDate":"1/1/2019",

    "MessageBoardId":4
}

Returns

{
    "id": 2,
    "text": "Posting my first message!",
    "user": "Jesse",
    "postedDate": "2019-01-01T00:00:00",
    "messageBoardId": 4,
    "messageBoard": null
}

I would expect that the messageBoard would not be null, and it would instead return the JSON for the messageBoard that was previously created. If I change to a GET method, it is also null. Why is it null?

编辑:这是我的控制器。我删除了除 GET 和 POST.

之外的操作
[Route("api/[controller]")]
[ApiController]
public class MessageBoardsController : ControllerBase
{
        private readonly MessageBoardContext _context;

        public MessageBoardsController(MessageBoardContext context)
        {
            _context = context;
        }

        // GET: api/MessageBoards/5
        [HttpGet("{id}")]
        public async Task<ActionResult<MessageBoard>> GetMessageBoard(long id)
        {
            var messageBoard = await _context.MessageBoards.FindAsync(id);

            if (messageBoard == null)
            {
                return NotFound();
            }

            return messageBoard;
        }


        // POST: api/MessageBoards
        [HttpPost]
        public async Task<ActionResult<MessageBoard>> PostMessageBoard(MessageBoard messageBoard)
        {
            _context.MessageBoards.Add(messageBoard);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetMessageBoard", new { id = messageBoard.Id }, messageBoard);
        }
}


[Route("api/[controller]")]
[ApiController]
public class MessagesController : ControllerBase
{
        private readonly MessageBoardContext _context;

        public MessagesController(MessageBoardContext context)
        {
            _context = context;
        }

        // GET: api/Messages/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Message>> GetMessage(long id)
        {
            var message = await _context.Messages.FindAsync(id);

            if (message == null)
            {
                return NotFound();
            }

            return message;
        }


        // POST: api/Messages
        [HttpPost]
        public async Task<ActionResult<Message>> PostMessage(Message message)
        {
            _context.Messages.Add(message);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetMessage", new { id = message.Id }, message);
        }
}

您已经提供了应用程序输出和数据库的外观,但没有提供关于如何 saves/retrieves 数据的中间部分。 在不知道中间发生了什么的情况下,我在黑暗中最好的尝试是你既没有正确设置延迟加载也没有使用 Include 来包含 MessageBoard 实体。

关于它们的更多信息here

你需要load related data

例如,对于您的 MessageBoard GET - // GET: api/MessageBoards/5

更改自:

var messageBoard = await _context.MessageBoards.FindAsync(id);

var messageBoard = await _context.MessageBoards
                        .Include(i=>i.Messages)
                        .FirstOrDefaultAsync(i => i.Id == id);

I would expect that the messageBoard would not be null, and it would instead return the JSON for the messageBoard that was previously created. If I change to a GET method, it is also null. Why is it null?

这是因为您返回的是新创建的消息,这里只有 MessageBoadId 存在,没有 MessageBoad 对象。因此,您必须使用 Include 为新创建的消息从数据库加载相关的 MessageBoad

你的PostMessage方法应该如下:

// POST: api/Messages
[HttpPost]
public async Task<ActionResult<Message>> PostMessage(Message message)
{
    _context.Messages.Add(message);
    await _context.SaveChangesAsync();

    var message = await _context.Messages
                    .Include(i=>i.MessageBoard)
                    .FirstOrDefaultAsync(i => i.Id == message.Id);

    return Json(message);
}