tags:

views:

48

answers:

2

How can I search in a table if a record with specific parameter doesn't exist, and then insert the record into table?

+1  A: 
if(from t in context.table where t.field.Equals(parameter) select t).Count() == 0)
{
  table t = new table(){ field1 = param1, field2 = param2};
  context.table.InsertOnSubmit(t);
  context.SubmitChanges();
}

And remember to enclose it in a transaction for possible concurrency issues.

despart
+2  A: 
MyDataContext db = new MyDataContext();

if (db.table.Where( x => x.ID == id).ToList().Count == 0 )
{
db.table.Add(MyRow);
context.SubmitChanges();
}
Paul Creasey
if (db.table.SingleOrDefault(x => x.ID == id) == null) would be faster.
rob_g
Assuming ID is the primary key then this would be OK, if it wasn't a PK then your code would throw exception when there are more than one match. What makes you say it would be faster?
Paul Creasey