0

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"
}
  • 2
    Does this answer your question? [ModelState Errors for all Navigation Properties](https://stackoverflow.com/questions/55115319/modelstate-errors-for-all-navigation-properties), [How to overcome Asp.net MVC validation error for navigation property](https://stackoverflow.com/q/37492300/8017690) – Yong Shun Jun 10 '22 at 12:16
  • Is View Model really required tho.. since I have both `FriendId` and `Friend` on my `VideoCollection`.. shuldn't it be handled appropriately? – Ashish Bhattarai Jun 10 '22 at 12:51

1 Answers1

0

You should use ViewModels and then you can map it by using AutoMapper or manually (How to use 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)
}

After this, you should map it... Don't use any of the navigation properties while adding or something like that.

serhatyt
  • 180
  • 2
  • 14