自动验证外键无法使用Core 2.1

时间:2018-07-27 14:44:39

标签: c# mysql .net-core

我正在尝试在.Net-Core 2.1中设置API。我一直在关注这个guide,并遇到模型无法自动验证的问题(根据Microsoft docs)。具体来说,我想确保,如果使用不存在的ForeignKey发送POST请求,我应该得到BadRequest响应。如果发送了正确的ForeignKey,则请求将得到正确处理。

操作
发送POST请求以添加不存在的CustomerId的Campaign。

预期
收到BadRequest响应

实际
由于未处理的DbUpdateException,API崩溃了。

我的文件如下:

Context.cs

    public class Context : DbContext
    {
         public Context(DbContextOptions<Context> options)
       : base(options)
        { }

    public DbSet<Customer> Customers { get; set; }
    public DbSet<Campaign> Campaigns { get; set; }
    }

Campaign.cs

    public class Campaign
    {
        public long Id { get; set; }
        public long CustomerId { get; set; }
        public Customer Customer { get; set; }

    }

Customer.cs

{
    public class Customer
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public List<Campaign> Campaigns { get; set; }
    }
}

CampaignController.cs

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

        public CampaignController(Context context)
        {
            _context = context;
        }

        //Get Methods

        [HttpPost]
        public IActionResult Create(Campaign campaign)
        {
            _context.Campaigns.Add(campaign);
            _context.SaveChanges();
            return CreatedAtRoute("GetCustomer", new { id = campaign.Id }, campaign);
        }

    }

Startup.cs

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        var connection = @"Server=(localdb)\mssqllocaldb;Trusted_Connection=True;ConnectRetryCount=0";
        services.AddDbContext<Context>(options => options.UseSqlServer(connection));
    }

1 个答案:

答案 0 :(得分:0)

不应该这样工作。控制器不会验证您的数据库外键。此处的验证用于验证您的ViewModel约束,例如[Required],...

文档:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1