gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:23:34 25 4
gpt4 key购买 nike

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

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 Controller 。迁移似乎正确地检测了两个模型之间的关系:

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 创建一条消息时,它们似乎没有正确链接。在 PostMan 中,我正在执行以下操作:

1) 发布一个新的留言板

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

主体 - 原始 - Json

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

返回

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

2) 发布新消息

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

主体 - 原始 - JSON

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

"MessageBoardId":4
}

返回

{
"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?

编辑:这是我的 Controller 。我删除了除 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);
}
}

最佳答案

您需要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);

关于c# - 具有外键关系的 ASP.NET Core Web API 和 EF Core 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54596180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com