我的问题有两个部分,如何做,以及它是否是好的风格。
TestDataBaseEntities
是正在传递的 DBContext 项。myQuery
是正在执行和读取的查询StatusMessage
从函数中传递给 UI 以报告操作是否成功。Records
是我需要帮助弄清楚的。我需要弄清楚如何将每条记录传递回ReadMan()
.
我在想一个 2d 字符串数组被传回会让我受益,因为我可以让这个DataAccess
类读取数据,并准备在我的UserInterface
类中显示。但问题就在于此。
要声明string[,]
,我需要知道字符串的大小,或者通过这样做隐含地给它尺寸Records[,] = new string[,] { { FirstField, SecondField }, { FirstField, SecondField } ... }
等等,但是不能,因为读入的第一条记录没有提供需要告诉的信息Records
它的第二个索引应该有多大[ , ThisIndex]
,如果我有这个工作,我会将 2d 传递Records
回UserInterface
类以显示给用户。
为什么要有这个Read功能?因为我应该将 EF 函数与 UI 分开,对吗?
public class DataAccess
{
public bool ReadMan(TestDatabaseEntities dbEntities, IQueryable myQuery, out string StatusMessage, out string[,] Records)
{
string ErrorMessage;
bool bSuccessful;
string[] ThisRecord;
bSuccessful = TryDataBaseAction(dbEntities, out ErrorMessage,
() =>
{
foreach (Man m in myQuery)
{
// was thinking ThisRecord could be temporary storage but doesn't seem to work to my benefit.
ThisRecord = new string[] { m.ManID.ToString(), m.Name };
}
});
if (bSuccessful)
StatusMessage = "Records read successfully";
else
StatusMessage = ErrorMessage;
return bSuccessful;
}
public bool TryDataBaseAction(TestDatabaseEntities MyDBEntities, out string ErrorMessage, Action MyDBAction)
{
UserInterface MyUI = new UserInterface();
try
{
MyDBAction();
ErrorMessage = "No Error";
return true;
}
catch (Exception e)
{
ErrorMessage = e.ToString();
return false;
}
}
}
编辑:固定
public bool ReadMan(TestDatabaseEntities dbEntities, IQueryable myQuery, out string StatusMessage, out string[,] Records)
{
string ErrorMessage;
bool bSuccessful;
string[,] TheseRecords = null;
// hands an Action() to TryDataBase, as indicated by lambda expression in 3rd arguement.
bSuccessful = TryDataBaseAction(dbEntities, out ErrorMessage,
() =>
{
List<Man> men = myQuery.OfType<Man>().ToList();
TheseRecords = new string[men.Count, 2];
// ERROR BELOW: Operator '<' cannot be applied to operands of type 'int' and 'method group'
for (int i = 0; i < men.Count; i++)
{
TheseRecords[i, 0] = men[i].ManID.ToString();
TheseRecords[i, 1] = men[i].Name;
}
});
Records = TheseRecords;
if (bSuccessful)
StatusMessage = "Records read successfully";
else
StatusMessage = ErrorMessage;
return bSuccessful;
}