使用LINQ从类层次结构中选择项目

时间:2013-01-15 12:36:21

标签: c# linq .net-4.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; }
    ...
}

elipsis代表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

1 个答案:

答案 0 :(得分:2)

在这种情况下,

linkedConstraints永远不会是null,因为它是lambda。

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

linkedConstraints.Any();

修改

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