Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

c# - Create / Update, and Read Child Entity ASP.NET Web API

I have been stuck on this problem for a while, and I am not sure how to go forwards with it.

I am using ASP.NET Web API and Entity Framework.

What I want to accomplish, is to create an restful API that will allow me to insert a multiple members into one Gym record. I have managed to return a list of members into my object Gym, but now I am not sure how to go about creating a records of the child entity Member.

Here are my models:

Gym

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace GymManagerAPI.Models
{
    public class Gym
    {
        [Required]
        public int GymID { get; set; }
        [Required]
        public string GymName { get; set; }
        public string GymDescription { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        [Required]
        public string State { get; set; }
        public string PostCode { get; set; }
        [Required]
        public string Country { get; set; }
        public virtual ICollection<Member> Members { get; set; }
    }
}

Member

using System;
using System.ComponentModel.DataAnnotations;

namespace GymManagerAPI.Models
{
    public class Member
    {
        [Required]
        public int MemberID { get; set; }
        [Required]
        public string MemberName { get; set; }
        [Required]
        public string MemberSurName { get; set; }
        public bool isActive { get; set; }
        [Required]
        public string Gender { get; set; }
        public DateTime DateOfBirth { get; set; }
        public DateTime DateOfEnrollment { get; set; }
        public DateTime DateOfCancelation { get; set; }
        public virtual Gym Gym { get; set; }


    }
}

Here are my Controllers:

GymsController.cs

[Route("api/[controller]")]
    [ApiController]
    public class GymsController : ControllerBase
    {
        private readonly GymManagerBackEndWebApiContext _context;

        public GymsController(GymManagerBackEndWebApiContext context)
        {
            _context = context;
        }

        // GET: api/Gyms
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Gym>>> GetGym()
        {
            return await _context.Gym.Include(p => p.Members).ToListAsync();
        }

        // GET: api/Gyms/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Gym>> GetGym(int id)
        {
            var gym = await _context.Gym.FindAsync(id);

            if (gym == null)
            {
                return NotFound();
            }

            return gym;
        }

        // PUT: api/Gyms/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPut("{id}")]
        public async Task<IActionResult> PutGym(int id, Gym gym)
        {
            if (id != gym.GymID)
            {
                return BadRequest();
            }

            _context.Entry(gym).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GymExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Gyms
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPost]
        public async Task<ActionResult<Gym>> PostGym(Gym gym)
        {
            _context.Gym.Add(gym);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetGym", new { id = gym.GymID }, gym);
        }
       

        // DELETE: api/Gyms/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<Gym>> DeleteGym(int id)
        {
            var gym = await _context.Gym.FindAsync(id);
            if (gym == null)
            {
                return NotFound();
            }

            _context.Gym.Remove(gym);
            await _context.SaveChangesAsync();

            return gym;
        }

        private bool GymExists(int id)
        {
            return _context.Gym.Any(e => e.GymID == id);
        }
    }
}

MembersController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using GymManagerBackEndWebApi.Models;

namespace GymManagerBackEndWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MembersController : ControllerBase
    {
        private readonly GymManagerBackEndWebApiContext _context;

        public MembersController(GymManagerBackEndWebApiContext context)
        {
            _context = context;
        }

        // GET: api/Members
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Member>>> GetMember()
        {
            return await _context.Member.ToListAsync();
        }

        // GET: api/Members/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Member>> GetMember(int id)
        {
            var member = await _context.Member.FindAsync(id);

            if (member == null)
            {
                return NotFound();
            }

            return member;
        }

        // PUT: api/Members/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPut("{id}")]
        public async Task<IActionResult> PutMember(int id, Member member)
        {
            if (id != member.MemberID)
            {
                return BadRequest();
            }

            _context.Entry(member).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MemberExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Members
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPost]
        public async Task<ActionResult<Member>> PostMember(Member member)
        {

      
            _context.Member.Add(member);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetMember", new { id = member.MemberID }, member);
        }

        // DELETE: api/Members/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<Member>> DeleteMember(int id)
        {
            var member = await _context.Member.FindAsync(id);
            if (member == null)
            {
                return NotFound();
            }

            _context.Member.Remove(member);
            await _context.SaveChangesAsync();

            return member;
        }

        private bool MemberExists(int id)
        {
            return _context.Member.Any(e => e.MemberID == id);
        }

I would love if someone more experienced dealing with navigation properties would help me, and push me towards my solution.

question from:https://stackoverflow.com/questions/65897785/create-update-and-read-child-entity-asp-net-web-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...