簡體   English   中英

如何在 asp.net 核心中找到屬性的總和

[英]How can i find the sum of an attribute in asp.net core

如何編寫 controller 方法來獲取 AsComponent Class 中所有標記屬性的總和。 我想獲得Ascomponents的總分。 我想構建一個 controller 方法,以便我可以將它與我的反應前端連接起來。

public class AsComponent
    {
        [Key]
        [ScaffoldColumn(false)]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int AsID { get; set; }
        public string Ascomponent { get; set; }

        [ForeignKey("LOID")]
        public int? Lid { get; set; } 
        public string LOID { get; set; }
        [ForeignKey("POId")]
        public string? POID { get; set; }
        public int Marks { get; set; }
        public string LD { get; set; }
        public string Type { get; set; }
    }

這是我的 controller。 它是自動生成的,我已經做了一些編輯。

namespace GroupProject.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AsComponentsController : ControllerBase
    {
        private readonly ObeDbContext _context;

        public AsComponentsController(ObeDbContext context)
        {
            _context = context;
        }

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

        // GET: api/AsComponents/5
        [HttpGet("{id}")]
        public async Task<ActionResult<AsComponent>> GetAsComponent(int id)
        {
            var asComponent = await _context.AsComponents.FindAsync(id);

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

            return asComponent;
        }

        // POST: api/AsComponents
        [HttpPost]
        public async Task<ActionResult<AsComponent>> PostAsComponent(AsComponent asComponent)
        {
            _context.AsComponents.Add(asComponent);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetAsComponent", new { id = asComponent.AsID }, asComponent);
        }

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

            _context.AsComponents.Remove(asComponent);
            await _context.SaveChangesAsync();

            return asComponent;
        }

        private bool AsComponentExists(int id)
        {
            return _context.AsComponents.Any(e => e.AsID == id);
        }
    }
}

將 Marks 屬性總結在一起就足夠了:

var marksSum = _context.AsCompoments.Sum(component => component.Marks)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM