简体   繁体   中英

relation one to many in asp.net core webapi

I'm new in asp.net and this is my first project . i have two table student and notes . student has many notes so i want to display list of student with their list of notes but i got this error in postmen There was an error parsing JSON data Unexpected end of JSON input. and in console Self referencing loop detected for property 'student' with type 'firstExp.Models.Student'. Path '[0].notes[0]'.

this is student model

public class Student
    {
         public int StudentId { get; set; }
         [Required]
        public string FirstName { get; set; }
         [Required]
        public string LastName { get; set; }

        public string City { get; set; }
        public string State { get; set; }
          public ICollection<Notes> Notes { get; set; }
               = new List<Notes>();
    }

this is notes model

 public class Notes {
        public int NotesId { get; set; }
         [Required]
        public string NoteValue { get; set; }
         [Required]

        public string Subject { get; set; }

        [ForeignKey ("StudentId")]
        public Student Student { get; set; }
        public int StudentId { get; set; }
    }

and this is student controller

namespace firstExp.Controllers
{
   [Route("api/[controller]")]
    [ApiController]
    public class StudentController : Controller
    {
        private StudentContext _studentContext;

        public StudentController(StudentContext context)
        {
            _studentContext = context;
        }

        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<Student>> Get()
        {
            return _studentContext.Students.OrderBy(c => c.FirstName).Include(c => c.Notes).ToList();
        }

}

}
this is OnModelCreating  method

  protected override void OnModelCreating (ModelBuilder builder) {
            base.OnModelCreating (builder);

            builder.Entity<Student> ().ToTable ("Students");
            builder.Entity<Student> ().HasKey (p => p.StudentId);
            builder.Entity<Student> ().Property (p => p.StudentId).IsRequired ().ValueGeneratedOnAdd ();
            builder.Entity<Student> ().Property (p => p.FirstName).IsRequired ().HasMaxLength (30);
            builder.Entity<Student> ().HasMany (p => p.Notes).WithOne (p => p.Student).HasForeignKey (p => p.StudentId);

            builder.Entity<Notes> ().ToTable ("Notes");
            builder.Entity<Notes> ().HasKey (p => p.NotesId);
            builder.Entity<Notes>().Property(p => p.NotesId).IsRequired().ValueGeneratedOnAdd();
              builder.Entity<Notes>().Property(p => p.NoteValue).IsRequired().HasMaxLength(50);
             builder.Entity<Notes>().Property(p => p.Subject).IsRequired();
        }
    }

what i'm doing wrong? thanks.

Your Notes class:

 public class Notes {
    public int NotesId { get; set; }
     [Required]
    public string NoteValue { get; set; }
     [Required]

    public string Subject { get; set; }


    public Student Student { get; set; }
    [ForeignKey ("Student")]        
    public int StudentId { get; set; }
}

In your SchollContext class, override the DbContext.OnModelCreating() and in there you shall define the relationships you want. Check the docs to see how you can do that. In your SchoolContext class declare the DbSets:

public DbSet<Student> Students { get; set; }
    public DbSet<Notes> Notes { get; set; }

And your OnModelCreating() should look like this one:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Notes>().HasOne<Student>(n => n.Student)
            .WithMany(s => s.Notes)
            .OnDelete(DeleteBehavior.Cascade);
        modelBuilder.Entity<Student>().ToTable("Students");
        modelBuilder.Entity<Notes>().ToTable("Notes");
        base.OnModelCreating(modelBuilder);
    }

Now, delete all of your migrations and delete the tables or the db, and apply the migrations again. Hope that helps!

You can configure Json.NET to ignore cycles that it finds in the object graph. This is done in the ConfigureServices method in Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    ...

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

    ...
}

Refer to Related data and serialization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM