linq to sql 更新标准
所以我知道关于如何使用 linq to SQL 更新数据库有很多问题,我的问题是,我是否按照公认的标准这样做?
这是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//load data to page
}
else
{
using (var db = new App_Data.MyDataContext())
{
var Query = (from p in db.peoples
where p.ipeople_ID == 59225
select p).Single();
Query.cFirstName = FirstName.Value;
try { db.SubmitChanges(); }
catch (ChangeConflictException)
{
db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
db.SubmitChanges();
}
}
}
}
我正在通过反复试验(以及大量的谷歌搜索!)来学习asp.net,所以我知道它会起作用,只是不知道代码是否会让我在会议上被笑! :D
谢谢
So I know there are many questions on how to update a DB with linq to SQL, my question is, am I doing this in an accepted standard?
here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//load data to page
}
else
{
using (var db = new App_Data.MyDataContext())
{
var Query = (from p in db.peoples
where p.ipeople_ID == 59225
select p).Single();
Query.cFirstName = FirstName.Value;
try { db.SubmitChanges(); }
catch (ChangeConflictException)
{
db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
db.SubmitChanges();
}
}
}
}
I am learning asp.net by trial and error (and lots of google searches!) so i know it will work, just don't know if the code would get me laughed out of a conference! :D
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一些更改:
我会将您的逻辑从页面加载事件移开,并显式触发保存/更新事件。
如果发生这种情况,我会解决更改冲突...我不会隐藏该错误并尝试重新提交更改。
Some changes:
I would move your logic away from the page load event, and explicitly trigger a save/update event.
I would address the change conflict if that is happening ... I wouldn't hide that error and attempt to resubmit changes.
从它的方法来看,这对我来说看起来相当标准。不过,我建议使用一种不同的、更简单的语法来获取单行:
这样,如果记录不存在,您将得到
NULL
。如果没有找到记录,Single
将抛出异常。我还将更新代码分成最少的按钮单击,直接在回发上更新人员似乎有点奇怪。我也喜欢局部变量使用小写变量,但我不会详细讨论这一点。
This looks fairly standard to me, in it's approach. However I would suggest a different, simpler syntax for fetching single rows:
This way, you will get
NULL
if the record doesn't exist.Single
will throw an exception if no record is found. I would also separate the update code out into a button click at minimum, updating the person directly on Post back seems a little odd.I also like lower-case variables for local variables, but I won't go into that.