0

我有一个包含几列的表,我想添加一个列而不首先为其提供值,因为它是一个(有点)复杂的对象,每次使用该表时可能都没有用。

所以我当前的代码如下所示:

            var com = new SqlConnection(functions.ConnectionString).CreateCommand();
            com.CommandText = @"
SELECT
    S.id
    , S.Name
    , S.MemberID
FROM dbo.SubSets AS S
WHERE S.SubsetType = 0
AND S.MemberId > 1
";
            this.tblSubsets = new DataTable();

            new SqlDataAdapter(com).Fill(this.tblSubsets);

            this.tblSubsets.Columns.Add(new DataColumn()
            {
                AllowDBNull = true
                , ColumnName = "Member"
                , DataType = typeof(object) // ?
                , DefaultValue = DBNull.Value // late binding mechanism?
            });

如何使该列Member在使用之前保持“空” DoSomethingwith(table.Rows[x]["Member"])

4

1 回答 1

0

我想你不能。

我最终存储了一个Func<T>并在将行添加到表时自动设置该字段。
加上闭包中的字典服务于性能目标。

            this.tblSubsets = new DataTable();

            this.tblSubsets.Columns.AddRange(new DataColumn[] {
                new DataColumn()
                {
                    AllowDBNull = false
                    , ColumnName = "Member"
                    , DataType = typeof(Func<Member>)
                }
            });

            var members = new Dictionary<int, Member>();
            this.tblSubsets.RowChanged += new DataRowChangeEventHandler((object sender, DataRowChangeEventArgs e) =>
            {
                if (e.Action != DataRowAction.Add)
                {
                    return;
                }

                e.Row["Member"] = new Func<Member>(() =>
                {
                    Member returnValue;
                    var mid = Convert.ToInt32(e.Row["MemberID"]);

                    if (!members.TryGetValue(mid, out returnValue))
                    {
                        members.Add(mid, (returnValue = new Member(mid)));
                    }

                    return returnValue;
                });
            });


            var com = new SqlConnection(functions.ConnectionString).CreateCommand();
            com.CommandText = @"
SELECT
    S.id
    , S.Name
    , S.MemberID
FROM dbo.SubSets AS S
WHERE S.SubsetType = 0
";
            new SqlDataAdapter(com).Fill(this.tblSubsets);
于 2013-07-08T09:16:08.933 回答