0

所有,我有一个 SQL 数据库类结构,如

public class Database : ISqlObject, IComparable<Database>, IEquatable<Database>
{
    public string Name { get; set; }
    public ISqlObject Parent { get; set; }
    public string Filename { get; set; }
    internal List<Schema> Schemas { get; set; }
    internal List<Table> Tables { get; set; }
    internal List<Constraint> Constraints { get; set; }

    public Database(string name, string filename)
    {
        this.Name = name;
        this.Parent = (ISqlObject)this;
        this.Filename = filename;
    }
    ...
}

protected internal class Table : ISqlObject, IComparable<Table>
{
    public string Name { get; set; }
    public ISqlObject Parent { get; set; }
    public List<Column> Columns { get; set; }
    ...
}

protected internal class Column : ISqlObject, IComparable<Column>
{
    public string Name { get; set; }
    public ISqlObject Parent { get; set; }
    public string Type { get; set; }
    public int MaxLength { get; set; }
    public bool IsNullable { get; set; }
    public bool HasConstraints { get; set; }
    public List<Constraint> Constraints { get; set; }
    ...
}

protected internal class Constraint : IComparable<Constraint>
{
    public string Name { get; set; }
    public ISqlObject Parent { get; set; }
    public bool IsPk { get; set; }
    public string LinkedConstraintName { get; set; }
    public string LinkedColumnName { get; set; }
    public string LinkedTableName { get; set; }
    ...
}

省略号代表IComparable实现和构造函数等。

我有以下代码使用 LINQ 返回当前列的相应约束,但我一直得到linkedConstraints = null

foreach (SqlServer.Column column in tableIndexDict[i].Columns)
{
    if (column.HasConstraints)
    {
        var linkedConstraints = 
            from table in database.Tables 
            from c in table.Columns 
            from con in c.Constraints 
                where con.LinkedTableName.Equals(tableIndexDict[i].Name) && 
                        con.LinkedColumnName.Equals(column.Name) 
            select con;
        foreach (SqlServer.Constraint c in linkedConstraints) <= HERE NullReference Exception.
        {

我在这里做错了什么?

注意:堆栈跟踪:

at System.Linq.Enumerable.<SelectManyIterator>d__31`3.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at UserCost.Export.QlikViewExporter.BuildExclusionTable(Database database) in 
f:\UserCost\UserCost\UserCost\Export\SqlDataExportFactory.cs:line 302
4

1 回答 1

2

linkedConstraints在这种情况下永远不可能null,因为它是 lambda。

您可以使用以下方法检查是否存在链接约束:

linkedConstraints.Any();

编辑

您必须检查检索到的数据。我假设con.LinkedTableNameorcon.LinkedColumnName为空。

于 2013-01-15T12:40:02.270 回答