我有一个包含几列的表,我想添加一个列,而不是首先为它提供一个值,因为它是一个(某种程度上)复杂的对象,每次使用该表时都可能没用。
所以我目前的代码如下:
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"])
之前保持“空”,该怎么办?
答案 0 :(得分: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);