简体   繁体   English

.Net Core Entity Framework 无法添加 http put 方法

[英].Net Core Entity Framework Can't add http put method

Prject.csproj, provides the following lines: Prject.csproj,提供以下几行:

    <Project Sdk="Microsoft.NET.Sdk.Web">
      <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
     </PropertyGroup>
     <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1"/>
        <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.0.0"/>
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0"/>
        <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="5.6.0"/>
        <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.6.0"/>
        <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0"/>
        <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0"/>
        <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0"/>
        <PackageReference Include="CloudinaryDotNet" Version="1.8.0"/>
        <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.1"/>
        <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="3.1.0"/>
        <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0"/>
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1"/>
     </ItemGroup>
   </Project> 

I'm using this model:我正在使用这个 model:

namespace Amaz.API.Models
{
    public class Cosa
    {
        public int Id {get; set;}
        public int UserId {get; set;}
        public string descripcion {get; set;}
    }
}

Which is designed this way in the DataContext.cs as far as EntityFramework is used:就使用 EntityFramework 而言,在 DataContext.cs 中以这种方式设计:

using Amaz.API.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace Amaz.API.Data
{
    public class DataContext : IdentityDbContext<User, Role, int, IdentityUserClaim<int>,
    UserRole, IdentityUserLogin<int>, IdentityRoleClaim<int>, IdentityUserToken<int>>
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options) {}

        public DbSet<Value> Values { get; set; }
        public DbSet<Photo> Photos { get; set; }
        public DbSet<Like> Likes { get; set; }
        public DbSet<Message> Messages { get; set; }
        public DbSet<Familiar> Familiars { get; set; }
        public DbSet<Situation> Situations { get; set; }

        public DbSet<Cosa> Cosas { get; set; }


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

             builder.Entity<UserRole>(userRole =>
             {
                 userRole.HasKey(ur => new {ur.UserId, ur.RoleId});

                 userRole.HasOne(ur => ur.Role)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.RoleId)
                    .IsRequired();

                 userRole.HasOne(ur => ur.User)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.UserId)
                    .IsRequired();   
             });

             builder.Entity<Like>()
                 .HasKey(k => new {k.LikerId, k.LikeeId});

              builder.Entity<Like>()
                 .HasOne(u => u.Likee)
                 .WithMany(u => u.Likers)
                 .HasForeignKey(u => u.LikeeId)
                 .OnDelete(DeleteBehavior.Restrict);

              builder.Entity<Like>()
                 .HasOne(u => u.Liker)
                 .WithMany(u => u.Likees)
                 .HasForeignKey(u => u.LikerId)
                 .OnDelete(DeleteBehavior.Restrict);

             builder.Entity<Message>()
                 .HasOne(u => u.Sender)
                 .WithMany(m => m.MessagesSent)
                 .OnDelete(DeleteBehavior.Restrict);

              builder.Entity<Message>()
                 .HasOne(u => u.Recipient)
                 .WithMany(m => m.MessagesReceived)
                 .OnDelete(DeleteBehavior.Restrict);
               
              builder.Entity<Photo>().HasQueryFilter(p => p.IsApproved);

              builder.Entity<Familiar>() 
                 .HasOne(u => u.Users)
                 .WithMany(m => m.Familiars)
                 .OnDelete(DeleteBehavior.Restrict); 
                         
              builder.Entity<Situation>(); 

              builder.Entity<Cosa>();
                
         }
    }
}

And the controller is: controller 是:

    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    using AutoMapper;
    using CloudinaryDotNet;
    using CloudinaryDotNet.Actions;
    using Amaz.API.Data;
    using Amaz.API.Dtos;
    using Amaz.API.Helpers;
    using Amaz.API.Models;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Options;
    
    namespace Amaz.API.Controllers
    {
        [ServiceFilter(typeof(LogUserActivity))]
        [Authorize]
        [Route("api/[controller]")]
        [ApiController]
        public class CosaController : ControllerBase
        {
            private readonly IVVRepository _repo;
            private readonly IMapper _mapper;
            public CosaController(IVVRepository repo, IMapper mapper)
            {
               
                _mapper = mapper;
                _repo = repo;
    
            }

            [HttpPost]
            public async Task<IActionResult> PutCosa(CosaDto CosaDto)
            {
                var CosaToCreate = _mapper.Map<Cosa>(CosaDto);
                _repo.Add(CosaToCreate);
    
                return NoContent();
            }

            [HttpGet("{id}")]
            public async Task<IActionResult> GetCosa (int id)
    
            {
    
                  var cosareturn = await _repo.GetCosa(id);
    
                  if (cosareturn == null)
                     return NotFound();
    
                  return Ok(cosareturn);
            }
    
            [HttpPut("{id}")]
            public async Task<IActionResult> UpdateCosa(int id, CosaDto CosaDto)
            {

    
                var cosa = await _repo.GetCosa(id);
    
                _mapper.Map(CosaDto, cosa);
                return NoContent();
            }
    
            [HttpDelete("{id}")]
            public async Task<IActionResult> DeleteCosa (int id)
    
            {            
                  var CosaFromRepo = await _repo.GetCosa(id);
                  _repo.Delete(CosaFromRepo);
    
                  return NoContent();
            }
        }
    }

But the main problem is that it is not possible to add a new register to the database through this "PutCosa" method.但主要问题是无法通过这种“PutCosa”方法将新寄存器添加到数据库中。 As Its tested in Postman:正如它在 Postman 中测试的那样: 邮递员屏幕截图在这里:

What could be failing here and how to solve it?什么可能在这里失败以及如何解决它?

In EF you actually need to Save your changes on the context so that EF will put the changes to the DB.在 EF 中,您实际上需要将更改保存在上下文中,以便 EF 将更改放入数据库。 See here https://docs.microsoft.com/en-us/ef/core/saving/basic请参阅此处https://docs.microsoft.com/en-us/ef/core/saving/basic

        [HttpPost]
        public async Task<IActionResult> PutCosa(CosaDto CosaDto)
        {
            var CosaToCreate = _mapper.Map<Cosa>(CosaDto);
            _repo.Add(CosaToCreate);
            _repo.SaveChanges();
            return NoContent();
        }

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

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