NULL values Unique Bug

Topics: Developer Forum
Aug 28, 2008 at 2:00 PM
I want to enforce such a constraint on a column that would ensure that the
values be all unique, but this wouldn't apply to NULL values.

when you allow null value and
your Validate() Function Will Check Null Value and report an Error.

But, I can Insert null when my db Index set Unique.

额,中文说一遍,就是数据库里索引设定为唯一(自动生成的表)并允许空值,然后在用你的验证函数的时候,插入2个空值会报错,而实际上插入数据库.Save的时候是没错的。
Aug 28, 2008 at 2:28 PM
解决办法是
namespace Lephone.Data
{
    public class ValidateHandler
    {
        private void validateUnique(object obj, Type t, ObjectInfo oi, bool IsNew)
        {
。。。。。

foreach (MemberHandler h in mhs)
                {
                   
                    object v = h.GetValue(obj);
                    if (h.AllowNull && v == null) { c = null; break; }
//加上上面这句话,意思是如果有一个值是空并且该字段允许空,则约束不起作用,实际上你在数据库中测试一下也是如此的.
                    if (v != null && v.GetType().IsGenericType)

------------------------------------------------------------------------

举个例子

-- Table: Table01

-- DROP TABLE Table01;

CREATE TABLE Table01 (
  Field01  integer PRIMARY KEY AUTOINCREMENT NOT NULL,
  Field02  integer NOT NULL,
  Field03  integer,
  Field04  integer
);

CREATE UNIQUE INDEX Table01_Index01
  ON Table01
  (Field02, Field03, Field04);

你可以插入
INSERT INTO Table01 (Field01, Field02, Field03, Field04) VALUES (1, 2, 3, 4);
INSERT INTO Table01 (Field01, Field02, Field03, Field04) VALUES (4, 2, 3, 0);
INSERT INTO Table01 (Field01, Field02, Field03, Field04) VALUES (5, 2, NULL, NULL);
INSERT INTO Table01 (Field01, Field02, Field03, Field04) VALUES (6, 2, NULL, NULL);
INSERT INTO Table01 (Field01, Field02, Field03, Field04) VALUES (7, 3, NULL, NULL);
INSERT INTO Table01 (Field01, Field02, Field03, Field04) VALUES (8, 2, NULL, NULL);
INSERT INTO Table01 (Field01, Field02, Field03, Field04) VALUES (9, 3, 3, NULL);
INSERT INTO Table01 (Field01, Field02, Field03, Field04) VALUES (10, 3, 3, NULL);

Coordinator
Aug 28, 2008 at 4:12 PM
Thank you.
Commited it. :)