updating list to DB with linq-to-sql
Supposed I have my data context MyDC and a list of objects called MyObject defined like this:
public class MyObject
{
public int ObjectID {get;set;}
public byte ObjectState {get;set;}
public string ObjectInJson {get;set;}
}
I'm writing a query for a table called ObjectsInJsonCache; the column names for this table are the same as the properties of the object. When I receive the list of MyObjects into the function, I want to either insert the item if it's not in the database or update the item if it already is.
The function for the query looks like this:
public static in CreateJsonCache(List<MyObject> TheListOfobjects)
{
int NumberOfObjectsLoaded = 0;
using ( MyDCdefinition MyDC = new MyDCdefinition())
{
ObjectsInJsonCache TheTable = new ObjectsInJsonCache();
//do I use a foreach loop?
//how do I switch insert/update?
// this?: MyD开发者_JAVA技巧C.ObjectsInJsonCache.InsertOnSubmit...
}
return NumberOfObjectsLoaded;
}
How do I write the query in linq-to-sql? In particular, if the list contains 1,000 items, I don't won't to talk to the DB 1,000 times so I'm wondering if using a foreach loop is the way to go. And what kind of query do I need? An InsertOnSubmit?
Thanks for your suggestions.
Generally, you would need 2 lists. 1 list which is already in the database and one list to update.
What you do is that you first is that you get all objects that are not in the database. What to do with these is simple, just InsertAllOnSubmit
.
You will need 2 database hits. First you get all the objects and then you submit changes.
It's hard to write complete code from your example, so I'm just going to explain.
To get all the items that are not in the db, you would take your input list and use Except. You might need a custom comparer if you are not using the object created by Linq. Also, if you have not set the id of the items not in the db, you can just check if ObjectID == default(int);
, if it is, it's a new one. But that depends on your ID handling.
To get the items that are already in the db, you should check Intersect. Then you loop trough them and then just update them.
No updates will be sent to the database until you use SubmitChanges
.
精彩评论