WebAPI 如何以 JSON 格式填充空结果

Posted

技术标签:

【中文标题】WebAPI 如何以 JSON 格式填充空结果【英文标题】:WebAPI How I Can Fill Empty Results in JSON Format 【发布时间】:2019-09-17 13:46:40 【问题描述】:

我有这样的结果:

但是正如您刚刚看到的,我的一些课程返回空结果。这是我的代码:

MyDBContext:

 public partial class MyContext : DbContext

    public MyContext()
        : base("name=MyContext")

    
       this.Configuration.ProxyCreationEnabled = false;
      //this.Configuration.LazyLoadingEnabled = false;
    

    public virtual DbSet<Announcement> Announcement  get; set; 
    public virtual DbSet<Class> Class  get; set; 
    public virtual DbSet<Discontinuity> Discontinuity  get; set; 
    public virtual DbSet<Grade> Grade  get; set; 
    public virtual DbSet<Group> Group  get; set; 
    public virtual DbSet<Lesson> Lesson  get; set; 
    public virtual DbSet<Management> Management  get; set; 
    public virtual DbSet<Payment> Payment  get; set; 
    public virtual DbSet<Questions> Questions  get; set; 
    public virtual DbSet<Student> Student  get; set; 
    public virtual DbSet<Teacher> Teacher  get; set; 

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    
        modelBuilder.Entity<Class>()
            .HasMany(e => e.Student)
            .WithOptional(e => e.Class)
            .HasForeignKey(e => e.Class_Id);

        modelBuilder.Entity<Group>()
            .HasMany(e => e.Student)
            .WithOptional(e => e.Group)
            .HasForeignKey(e => e.Group_Id);

        modelBuilder.Entity<Lesson>()
            .HasMany(e => e.Teacher)
            .WithRequired(e => e.Lesson)
            .HasForeignKey(e => e.Lesson_Id)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Student>()
            .HasMany(e => e.Discontinuity)
            .WithOptional(e => e.Student)
            .HasForeignKey(e => e.Student_Id);

        modelBuilder.Entity<Student>()
            .HasMany(e => e.Grade)
            .WithOptional(e => e.Student)
            .HasForeignKey(e => e.Student_Id);

        modelBuilder.Entity<Student>()
            .HasMany(e => e.Payment)
            .WithOptional(e => e.Student)
            .HasForeignKey(e => e.Student_Id);
    

我的控制器类:

public class StudentsController : ApiController

    private MyContext db = new MyContext();

    // GET: api/Students
    public IQueryable<Student> GetStudent()
    
        return db.Student;
    

    // GET: api/Students/5
    [ResponseType(typeof(Student))]
    public IHttpActionResult GetStudent(int id)
    
        Student student = db.Student.Find(id);
        if (student == null)
        
            return NotFound();
        

        return Ok(student);
    

    // PUT: api/Students/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutStudent(int id, Student student)
    
        if (!ModelState.IsValid)
        
            return BadRequest(ModelState);
        

        if (id != student.Id)
        
            return BadRequest();
        

        db.Entry(student).State = EntityState.Modified;

        try
        
            db.SaveChanges();
        
        catch (DbUpdateConcurrencyException)
        
            if (!StudentExists(id))
            
                return NotFound();
            
            else
            
                throw;
            
        

        return StatusCode(HttpStatusCode.NoContent);
    

    // POST: api/Students
    [ResponseType(typeof(Student))]
    public IHttpActionResult PostStudent(Student student)
    
        if (!ModelState.IsValid)
        
            return BadRequest(ModelState);
        

        db.Student.Add(student);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new  id = student.Id , student);
    

    // DELETE: api/Students/5
    [ResponseType(typeof(Student))]
    public IHttpActionResult DeleteStudent(int id)
    
        Student student = db.Student.Find(id);
        if (student == null)
        
            return NotFound();
        

        db.Student.Remove(student);
        db.SaveChanges();

        return Ok(student);
    

    protected override void Dispose(bool disposing)
    
        if (disposing)
        
            db.Dispose();
        
        base.Dispose(disposing);
    

    private bool StudentExists(int id)
    
        return db.Student.Count(e => e.Id == id) > 0;
    

我怎样才能填满我的外语课?我很好奇有没有办法在结果的开头输入类名。例如。如果我在 Student 它应该开始为:“Student”:[“Id”:18 ] 该类已经填写在数据库中。而且我已经有了模型构建器。但是我真的不知道我在哪里做错了?

【问题讨论】:

【参考方案1】:

您需要.Include 这些附加属性,这将指示 EF 去为您检索数据。

为此,您需要将语法稍微更改为:

var student = db.Student
    .Include(i => i.Discontinuity)
    .Include(i => i.Payment)
    .SingleOrDefault(s => s.Id == id);

【讨论】:

以上是关于WebAPI 如何以 JSON 格式填充空结果的主要内容,如果未能解决你的问题,请参考以下文章

.net中 webapi 返回结果为json格式

.net中 webapi 返回结果为json格式

如何通过填充 NSDictionary 以 JSON 格式发送 UIImage

csharp 从ASP.NET WebAPI控制器以camelCase格式返回JSON数据。

WebAPI返回JSON的正确格式

在 WebAPI 中返回空 json