Subsonic 3 - Insert of Update
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 bla开发者_Go百科h
}
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.
You should also be able to do it like this:
// perform insert with a linq expression
db.Insert.Into<PARTS_VI_PART_NUMBER>(
x => x.ITEM_NUMBER,
x => x.ITEM_CLASS_CODE,
x => x.ITEM_DESCRIPTION,
x => x.MANUFACTURER
).Values(
"TEST",
"TEST",
"TEST",
"TEST"
).Execute();
// update using linq expression
db.Update<PARTS_VI_PART_NUMBER>()
.Set(x => x.ITEM_DESCRIPTION == "UPDATED",
x => x.ITEM_CLASS_CODE == "UPDATED2")
.Where(x => x.ITEM_NUMBER == "TEST")
.Execute();
// delete inserted row with a linq expression
db.Delete<PARTS_VI_PART_NUMBER>(x => x.ITEM_NUMBER == "TEST").Execute();
At least that is how I've been doing it in one of my projects.
The Insert()
, Update()
and Delete()
methods are generated by Context.tt
into the Context.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.
精彩评论