【发布时间】:2017-11-14 06:36:54
【问题描述】:
我正在使用 ASP.NET Core 构建一个简单的娱乐应用,我目前只有一个 Post 模型和一个 User 模型。
Post.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
public class Post
{
[Required]
public int Id { get; set; }
[Required]
[MaxLength(16)]
public string Title { get; set; }
public string Body { get; set; }
[Required]
public Person Author { get; set; }
}
}
Person.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
public class Person
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
public ICollection<Post> Posts = new List<Post>();
}
}
我使用 Visual Studio 的脚手架为这些模型生成控制器。
当我尝试POST /api/posts 以创建新帖子时,我还想为该帖子指定Author ID。
我尝试添加属性authorId,我尝试了"authorId": 1 和"author": { "id": 1 },但由于需要作者,我总是返回Author is missing 或Email in author is missing 等。
如何在帖子正文中包含 authorId 以便我能够成功创建新帖子?
【问题讨论】:
-
能否请您在问题标题中总结您的问题,而不是用标签/关键字填充问题标题?花点时间阅读What are tags, and how should I use them?。一个好的标题可以总结您遇到的问题,帮助其他人发现您的问题,并仅从标题中查看他们是否有解决方案
-
您正在编辑数据,因此请始终使用视图模型,并且该视图模型将不包含
Author的属性,因为它不会被用户编辑。在 POST 方法中您初始化数据模型(如果编辑现有记录,则从数据库中获取)并根据视图模型设置其属性(并根据当前用户设置作者属性)What is ViewModel in MVC?
标签: c# asp.net-core asp.net-core-mvc