So, I'm exploring ASP.NET Core (WebAPI). I created 2 models, made context file, added a one-to-many relationship between classes Friend and VideoCollection. Now, when I try to post create data into both Tables, I get validation errors since I don't send the navigation fields from the browser. Models:
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 operation:
[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);
}
Response Body for every valid 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."
]
}
}
Request Body for POST videos
{
"movietitle": "movie",
"yearreleased": "1810",
"rating": "1.6",
"subject": "Violence",
"length": "1.8",
"note": "Bad film",
"friendid": "1"
}