简体   繁体   English

如何在使用相关实体时使用带有存储库模式的添加方法.Net Web API?

[英]How to use Add method with repository pattern while using related entities .Net Web API?

this is my product entity这是我的产品实体

public class Product : BaseEntity
    {
       public string ProductName { get; set; }
       public string Description { get; set; }
       public string Img1 { get; set; }
       public string Img2 { get; set; }
       public string Img3 { get; set; }
       public decimal Price { get; set; }
       public int Stock { get; set; }

       //    Related Entities

       public Category Category { get; set; }
       public int CategoryId { get; set; }

    }

Category entity类别实体

public class Category : BaseEntity
    {
        public string Name { get; set; }
        public string Img { get; set; }
        public string Description { get; set; }

    }

my IProductrepositoryinterface我的产品库界面

 public interface IProductRepository
    {
        Task<Product> GetProductByIdAsync(int id);
        Task<IReadOnlyList<Product>> GetProductsAsync();
        Task<bool> SaveChangesAsync();
        void Add(Product product);
        void Update(Product product);
        void Delete(Product product);

    }

product repository产品库

namespace Infrastructure
{
    public class ProductRepository : IProductRepository
    {
       private readonly StoreContext _context;

        public ProductRepository(StoreContext context)
        {
            _context = context;
        }

        public void Add(Product product)
        {
            _context.Add(product);
        }

        public void Delete(Product product)
        {
            _context.Remove(product);
        }

        public async Task<Product> GetProductByIdAsync(int id)
        {
            return await _context.Products.Include(c => c.Category)
            .FirstOrDefaultAsync(p => p.Id == id);
        }

        public async Task<IReadOnlyList<Product>> GetProductsAsync()
        {
            return await _context.Products.Include(p => p.Category).
            ToArrayAsync();
        }

        public async Task<bool> SaveChangesAsync()
        {
            return await _context.SaveChangesAsync().ConfigureAwait(false) > 0;
        }

        public void Update(Product product)
        {
            _context.Attach(product);
            _context.Entry(product).State = EntityState.Modified;
        }

ProductController Post method ProductController 发布方法

[HttpPost]
        public async Task<ActionResult> AddProduct(Product product)
        {
            try
            {
                if (product.Id == 0)
                {
                    var responseError = new ResponseError(StatusCodes.Status400BadRequest, "Fields cannot be empty.");
                    var response = new Response(false, null, responseError);
                    return BadRequest(response);
                }
                else
                {
                    _repository.Add(product);
                    await _repository.SaveChangesAsync();
                    var response = new Response(true, product, null);
                    return Ok(response);
                }

            }
            catch (Exception e)
            {
                var responseError = new ResponseError(StatusCodes.Status500InternalServerError, e.Message);
                var response = new Response(false, null, responseError);
                return StatusCode(StatusCodes.Status500InternalServerError, response);
            }
        }

当前json我们想要的发布方法 How can we change post method with only giving categoryName.我们如何通过仅提供 categoryName 来更改 post 方法。 What I m trying is making program understanding directly with category name without using categoryId?我正在尝试的是在不使用 categoryId 的情况下直接使用类别名称让程序理解?

So you want your HTTP request object to be different than your EF Entity.因此,您希望 HTTP 请求 object 与您的 EF 实体不同。 This is a common pattern.这是一种常见的模式。 Typical solution is to have a separate set of types that define the contract for your API and map back and forth to your EF Entity types.典型的解决方案是使用一组单独的类型来定义 API 和 map 与 EF 实体类型之间的契约。

See eg Create Data Transfer Objects (DTOs)参见例如创建数据传输对象(DTO)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 服务存储库模式,如何使用多个相关实体保存多个对象 - Service repository pattern, how to save multiple objects with many related entities Web API 2相关实体 - Web API 2 related entities 在 EF Core 通用存储库中使用 .Find() 方法加载相关实体 - Load related entities using .Find() method in an EF Core generic repository asp.net odata Web api $ select相关实体失败 - asp.net odata web api $select failing for related entities 如何在 Repository.Net 中使用多个 DataContexts(DbContext) Web API - How to use Multiple DataContexts(DbContext) in a Repository .Net Web API 何时在 .net 核心 web-api 上使用存储库模式的 async/await? - When use async/await on .net core web-api with repository pattern? 通用存储库模式 ASP NET CORE Web Api:使用包含异步 - Generic repository pattern ASP NET CORE Web Api: using include with async 如何在.Net 的存储库模式中使用流畅的验证? - How to use Fluent Validation in Repository Pattern in .Net? EF如何使用.include()和使用存储库模式查询更多实体 - EF How to query more entities with .include() and using repository pattern ASP.NET Web API打破了Repository / Services模式 - ASP.NET Web API breaking Repository/Services pattern
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM