【问题标题】:Unique constraint on nullable in System.Data.DataColumnSystem.Data.DataColumn 中可为空的唯一约束
【发布时间】:2012-05-30 11:43:58
【问题描述】:

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

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;

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

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

【问题讨论】:

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


【解决方案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);

【讨论】:

  • 不,默认为true(看你自己的链接)
  • 查看您的编辑:无论如何,这些类似乎在外键列上缺少某种唯一性概念(建模 (0-1)-(1) 关系
  • 我会将您的答案设置为已接受,因为我认为我们同意这在我看来是行不通的。不幸。
猜你喜欢
  • 2016-08-29
  • 1970-01-01
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多