System.Data.DataColumn中对nullable的唯一约束

时间:2012-05-30 11:43:58

标签: c# asp.net .net database unique-constraint

在我的数据库中,我有一个这样的表

table foo
int pk
int someFK NULL

对someFK使用外键约束,对someFK使用唯一约束。 这意味着在MySQL数据库中我有这个,除非我在someFK中指定NULL,当然在相应的表中必须有一行。但是,即使启用了唯一约束,我也可以在someFK中有几行NULL。

在我的代码中,我使用System.Data命名空间并执行如下操作:

DataTable table = new DataTable("Foo");

DataColumn col = null;

DataColumn[] primaryKey = new DataColumn[1];

col = table.Columns.Add(FooPropertyName, typeof(int));
col.Unique = true;
col.AutoIncrement = true;
primaryKey[0] = col;
table.PrimaryKey = primaryKey;

col = table.Columns.Add(SomeFkPropertyName, typeof(int));
col.Unique = true;
col.AutoIncrement = false;

但是,如果我向DataTable添加两个DataRows,并且这两个主键具有不同的主键但在someFK列上都有DBNull,则会收到错误消息 异常类型:System.Data.ConstraintException 异常消息:列'somefk'被约束为唯一。价值''已经存在。

这不是我所期望的,所以我想知道是否有人知道如何解决这个问题(不删除唯一属性)

1 个答案:

答案 0 :(得分:1)

您需要告诉DataTable接受空值。

col = table.Columns.Add(SomeFkPropertyName, typeof(int)); 
col.Unique = true; 
col.AutoIncrement = false; 
col.AllowDBNull = true;

更多AllowDBNull

修改1

你还是坏了,

        var table = new DataTable("Foo");
        table.Columns.AddRange(new []
        {
            new DataColumn("FooPropertyName", typeof(int))
            {
                Unique = true,
                AutoIncrement = true
            },
            new DataColumn("SomeFkPropertyName")
            {
                Unique = true,
                AllowDBNull = true
            },
        });
        table.PrimaryKey = new[] {table.Columns[0]};

        table.Rows.Add(0, 0);
        table.Rows.Add(1, 1);
        table.Rows.Add(2, DBNull.Value);
        table.Rows.Add(3, DBNull.Value); // Exception here

修改2

这也不起作用:/

private class MyDbNull
{
    public static MyDbNull Value = new MyDbNull();
    public override bool Equals(object obj)
    {
        return false;
    }

    public override int GetHashCode()
    {
        return 0;
    }
}

table.Rows.Add(2, MyDbNull.Value);
table.Rows.Add(3, MyDbNull.Value);
相关问题