实体框架6代码第一种方法 - 唯一约束不工作 [英] Entity Framework 6 Code First approach - unique constraint doesn't work

查看:163
本文介绍了实体框架6代码第一种方法 - 唯一约束不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用EF 6与代码第一的方法。除了数据库级别的数据库约束检查之外,我想在POCO级别提供唯一的约束检查。我已遵循文章实体框架6 - 使用流畅的API设置唯一约束?,有人建议使用[Index()]属性。

I am using EF 6 with code first approach. In addition to database constraints check at database level, I would like to provide unique constraints check at POCO level. I have followed article Entity Framework 6 - Setting unique Constraint with fluent API? where someone suggested to use [Index()] attribute. I have applied the same in my poco class but looks like it is still throwing an exception from Database level.

这是我的代码: / p>

Here is my code:

[Key]
public decimal OrderId { get; set; }

[Index("ORDER_CC", 2, IsUnique = true)]
public decimal? MemberId { get; set; }

[Index("ORDER_CC", 3, IsUnique = true)]
public decimal? ItemId { get; set; }

[Index("ORDER_CC", 1, IsUnique = true)]
public decimal? OrderNumber { get; set; }

public decimal? Cost { get; set; }

public DateTime Time { get; set; }

我不知道我在这里做错了什么?

I am not sure what I am doing wrong here?

我还想询问以下内容:


  1. 我需要保持相同的索引

  2. 我如何知道,它正在根据EF约束检查或数据库约束检查得到验证?

  3. 我对POCO类比较的顺序与数据库中Order表中定义的顺序保持不变。

数据库脚本:

CREATE UNIQUE INDEX xyz.ORDER_CC ON xyz.Order
(OrderNumber, MemberId, ItemId)
LOGGING
TABLESPACE USERS
PCTFREE    10
INITRANS   2
MAXTRANS   255
STORAGE    (
            INITIAL          128K
            NEXT             1M
            MINEXTENTS       1
            MAXEXTENTS       UNLIMITED
            PCTINCREASE      0
            BUFFER_POOL      DEFAULT
            FLASH_CACHE      DEFAULT
            CELL_FLASH_CACHE DEFAULT
           )
NOPARALLEL;

任何想法?

推荐答案

问题不在于Index属性,而是在你对它的作用的期望。

The problem is not in the Index attribute, it's in your expectations of what it does.

索引属性不验证唯一约束,它仅指示Entity Framework代码 - 首先在迁移期间在数据库中创建索引。从你的问题,显然你使用EF代码,即POCO和编码映射,但你使用一个预先存在的数据库。在这种情况下,应用索引属性是无用的。

The Index attribute doesn't validate a unique constraint, it only instructs Entity Framework code-first to create an index in the database during a migration. From your questions it is clear that you use EF code-first, i.e. POCO's and coded mappings, but you work with a preexisting database. In this case, applying index attributes is useless.

这也回答了你的问题在哪里检查约束:在数据库中。这就是为什么它仍然引发错误。如果你想在代码中有一个唯一的约束,你必须自己写。

So that also answers your question where the constraint is checked: in the database. And that's why it's still throwing errors. If you want a unique constraint in code you'll have to write it yourself.

这篇关于实体框架6代码第一种方法 - 唯一约束不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆