我正在使用Linq to SQL和存储过程来查询简单的数据库。在我的表单上,我有一个datagridview,其中包含一些查询字段的控件。用户键入街道名称/编号/方向等,然后在datagrid中返回结果。网格使用bindingSource和bindingNavigator来获取结果。我可以导航,将结果作为列表返回<>从我的DAL并调用更新存储过程,这很好。但是,当我使用内置命令添加新记录时,它成功地将记录添加到网格中,但是当我尝试在DataContext上的DAL中使用GetChangeSet时,我显示了0个插入。
因此DataContext正在跟踪我对现有记录的更改,但没有看到任何添加的记录。我在DAL中使用私有静态datacontext。我想问题是如何添加新记录并将其传递给我的存储过程方法?我没有看到任何方法从bindingsource“获取添加记录”,或者我怎么能使用网格来查看是否需要添加新记录?
调用我的DAL的UI /表单中的代码
private void btnSearch_Click(object sender, EventArgs e)
{
// Call search query
spSearchCardsResultBindingSource.DataSource =
SideSewer.QueryCards(permit:txtPermit.Text,
parcel: txtParcel.Text, streetNum: nullNum1,
streetNum2: nullNum2, streetDirection: cbDirection.Text,
streetName: txtName.Text, streetType: cbType.Text,
inspected: inspectedNull, includeAliases: ckbxAlias.Checked);
}
private void saveToolStripButton_Click(object sender, EventArgs e)
{
// This line below actually WORKS, yet it just adds the record
// user currently has selected may NOT be the NEW one!!
SideSewer.InsertData((PermitInfo)spSearchCardsResultBindingSource.Current);
if (!SideSewer.save())
MessageBox.Show("There was a problem saving the record(s)");
}
以下是查询记录和执行保存的代码。保存适用于更新,但每当我在网格中添加记录时,它都会将其添加到PermitInfo列表中,但不会显示在GetChangeSet中。
private static SideSewerDataContext _dc = new SideSewerDataContext();
public static List<PermitInfo> QueryCards(string permit = null,
string parcel = null, int? streetNum = null, int? streetNum2 = null,
string streetDirection = null,string streetName = null,
string streetType = null,DateTime? inspected = null, bool? includeAliases = null)
{
try
{
return dc.spSearchCards(permit, parcel, streetNum, streetNum2,
streetDirection, streetName, streetType, inspected, includeAliases).ToList();
}
catch (SqlException ex)
{
MessageBox.Show("Error: " + ex.Message,"Error Occured!",MessageBoxButtons.OK,MessageBoxIcon.Error);
return null;
}
}
public static bool save()
{
ChangeSet cs = _dc.GetChangeSet();
try
{
foreach (var obj in cs.Updates)
{
if (obj is PermitInfo)
{
PermitInfo pInfo = (PermitInfo)obj;
_dc.spUpdatePermitInfo(pInfo.ID, pInfo.Permit, pInfo.Parcel, pInfo.StreetNumber, pInfo.StreetNumberSuffix, pInfo.StreetDirection, pInfo.StreetName, pInfo.StreetType, pInfo.Inspected, Environment.UserName.ToUpper());
}
}
foreach (var obj in cs.Inserts)
{
if (obj is PermitInfo)
{
PermitInfo pInfo = (PermitInfo)obj;
_dc.spInsertPermitInfo(Environment.UserName.ToUpper(), pInfo.Permit, pInfo.Parcel, pInfo.StreetNumber, pInfo.StreetNumberSuffix, pInfo.StreetDirection, pInfo.StreetName, pInfo.StreetType, pInfo.Inspected);
}
}
return true;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return false;
}
}
提前感谢任何看过这个的人,并且能够让我深入了解我做错了什么或者如何解决我需要完成的事情!!