在我的数据库中,我有一个这样的表
table foo
int pk
int someFK NULL具有对someFK的外键约束和对someFK的唯一约束。这意味着在MySQL数据库中,除非我在someFK中指定NULL,否则在相应的表中当然必须有一行。但是,即使unique约束为on,我也可以在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‘被约束为唯一。值'‘已存在。
这不是我所期望的,所以我想知道是否有人知道如何解决这个问题(不删除唯一的属性)
发布于 2012-05-30 20:00:00
您需要告诉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);https://stackoverflow.com/questions/10815629
复制相似问题