Friend字段是必需的.(导航属性字段)



所以,我正在探索ASP。. NET Core (WebAPI)。我创建了2个模型,制作了上下文文件,在类FriendVideoCollection之间添加了一对多关系。现在,当我尝试将创建数据发布到两个表中时,我得到了验证错误,因为我没有从浏览器发送导航字段。模型:

public class Friend
{
public int Id { get; set; }
.....
public virtual IEnumerable<VideoCollection> videoCollections { get; set; }
}
public class VideoCollection
{
public int Id { get; set; }
......
public int FriendId { get; set; }
public virtual Friend Friend { get; set; }
}

My Context Class:

public class WebApiMySQLContext : DbContext
{
public WebApiMySQLContext(DbContextOptions<WebApiMySQLContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Friend>()
.HasMany(f => f.videoCollections)
.WithOne(v => v.Friend)
.HasForeignKey(v => v.FriendId)
.IsRequired();
}
public DbSet<Friend> Friends { get; set; } = null!;
public DbSet<VideoCollection> Videos { get; set; } = null!;
}

And Controller for POST操作:

[HttpPost]
public async Task<ActionResult<VideoCollection>> PostVideoCollection(VideoCollection videoCollection)
{
if (_context.Videos == null)
{
return Problem("Entity set 'WebApiMySQLContext.Videos'  is null.");
}
_context.Videos.Add(videoCollection);
await _context.SaveChangesAsync();
return CreatedAtAction("GetVideoCollection", new { id = videoCollection.Id }, videoCollection);
}

每个有效POST的响应体

{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-6d1fcffc19ecf7f8e9bbf5eed016d842-f3712183c476ca8d-00",
"errors": {
"Friend": [
"The Friend field is required."
]
}
}

POST视频请求正文

{
"movietitle": "movie",
"yearreleased": "1810",
"rating": "1.6",
"subject": "Violence",
"length": "1.8",
"note": "Bad film",
"friendid": "1"
}

你应该使用ViewModels,然后你可以通过使用AutoMapper或手动映射它(如何使用AutoMapper)

public class FriendViewModel
{
public int Id {get;set;}
.....
(WITHOUT IEnumerable<VideoCollection> videoCollections property)
}
public class VideoCollectionViewModel
{
public int Id { get;set;}
...
public int FriendId {get;set;}
(WITHOUT Friend property)
}

在这之后,你应该映射它…在添加或类似的东西时不要使用任何导航属性。

最新更新