Subsonic 3 - 更新插入
目前正在使用 Subsonic 3 和 Activerecord。纯粹出于好奇,是否有一种简单的方法可以以干净简洁的方式更新或插入记录?
而不是
var record = MyModal.SingleOrDefault(x => x.id == 1)
if (record != null)
{
// code to update record here
} else {
// code to insert a record here
MyModal record = new MyModal();
record.attribute1 = "blah"
... blah blah
}
Currently using Subsonic 3 with Activerecord. Purely out of curiosity, is there an easy way to update or insert a record in a clean and consise way?
Instead of
var record = MyModal.SingleOrDefault(x => x.id == 1)
if (record != null)
{
// code to update record here
} else {
// code to insert a record here
MyModal record = new MyModal();
record.attribute1 = "blah"
... blah blah
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标准 ActiveRecord 模板提供了 Save() 方法,该方法根据对象是否为 IsNew() 来调用 Add() 或 Update()。它应该适用于您提供的示例。
The standard ActiveRecord templates provide a Save() method, which either calls Add() or Update() depending on whether the object IsNew(). It should work in the sample you gave.
您还应该能够这样做:
至少我在我的一个项目中就是这样做的。
Insert()
、Update()
和Delete()
方法由Context.tt
生成到 < code>Context.cs 文件(我使用的是“ActiveRecord”T4 文件)。编辑
哦,很抱歉,当我第一次读到你的问题时,我以为你是在要求一种更简单的方法来“插入”或“更新”,但在重新阅读后阅读它,我意识到您正在要求“插入,或更新,如果它已经存在”就像执行“更新插入”一样。
抱歉,我的回答并没有真正涵盖这一点。我也不知道有什么好的方法。我通常只是做你正在做的事情......尝试选择它,如果我没有得到结果,则进行插入。
You should also be able to do it like this:
At least that is how I've been doing it in one of my projects.
The
Insert()
,Update()
andDelete()
methods are generated byContext.tt
into theContext.cs
file (I am using the "ActiveRecord" T4 files).Edit
Oh I'm sorry, when I forst read your question, I thought you were asking for an easier way to "Insert" or "Update", but after re-reading it, I realized you are asking for "Insert, or Update if it already exists" like doing an 'upsert'.
Sorry, my answer doesn't really cover that. I don't know of a good way to do it either. I usually just end up doing what you are doing... try to select it, and if I get no results, do the insert.