模型的索引无效

时间:2019-04-23 19:16:52

标签: asp.net-core entity-framework-core

postgres中的表格:

CREATE TABLE "public"."filters" (
  "Id" int4 NOT NULL DEFAULT nextval('"filters_Id_seq"'::regclass),
  "Name" varchar(200) COLLATE "pg_catalog"."default" NOT NULL DEFAULT ''::character varying,
  "Type" int4 NOT NULL,
  "Alias" varchar(200) COLLATE "pg_catalog"."default" NOT NULL DEFAULT ''::character varying
)
;

-- ----------------------------
-- Indexes structure for table filters
-- ----------------------------
CREATE UNIQUE INDEX "filters_unique_alias_key" ON "public"."filters" USING btree (
  "Alias" COLLATE "pg_catalog"."default" "pg_catalog"."text_ops" ASC NULLS LAST
);
CREATE UNIQUE INDEX "filters_unique_name_key" ON "public"."filters" USING btree (
  "Name" COLLATE "pg_catalog"."default" "pg_catalog"."text_ops" ASC NULLS LAST
);

-- ----------------------------
-- Primary Key structure for table filters
-- ----------------------------
ALTER TABLE "public"."filters" ADD CONSTRAINT "filters_primary_key" PRIMARY KEY ("Id");

型号:

[Table("filters")]
    public class Filter
    {
        [Key] public int Id { get; set; }

        [Required]
        [StringLength(200)]
        public string Name { get; set; }

        [Required]
        [StringLength(200)]
        public string Alias { get; set; }

        [Required] public FilterType Type { get; set; }
    }

    public enum FilterType
    {
        Logic = 0,
        Text = 1,
        Number = 2
    }

上下文:

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

            builder.Entity<Filter>().HasIndex(model => model.Name).HasName("filters_unique_name_key").IsUnique();
            builder.Entity<Filter>().HasIndex(model => model.Alias).HasName("filters_unique_alias_key").IsUnique();
        }

我正在使用非唯一值发出请求,并从postgres接收DbUpdateException:

public IActionResult Create(Filter filter = null)
        {
            if (ModelState.IsValid && filter != null)
            {

                // code

            }
        }

为什么如果我通过流利的api定义索引,则modelstate是有效的,但是索引验证不起作用?似乎EF核心忽略了索引验证,但为什么呢?如何验证?

2 个答案:

答案 0 :(得分:0)

独特的索引流利的API配置不会影响模型验证。如果不查询数据库,就无法知道特定的发布值是否唯一,这不是Modelbinder有权执行甚至不应该执行的操作。如果要为此添加验证,则需要手动进行。

var filter = await _context.Filters.FirstOrDefaultAsync(x => x.Name == model.Name || x.Alias == model.Alias);
if (filter?.Name == model.Name)
    ModelState.AddModelError(nameof(model.Name), "Name must be unique.");
if (filter?.Alias == model.Alias)
    ModelState.AddModelError(nameof(model.Alias), "Alias must be unique.");

答案 1 :(得分:0)

ModelState无法验证模型构建器的规则。

Fluent API用于配置域类以覆盖约定。使用Validation attributes(数据注释)进行自动验证或手动进行