- I read a set of data from database first
- Insert a new record using same data in same table.
I tried this but:-
using (var db = new
DataContext(ConfigurationManager.ConnectionStrings["DB"].ToString()))
{
var items = from t in db.Table1
where t.ID.Equals(100)
select t;
foreach (var item in items)
{
using (var db1 = new
DataContext(ConfigurationManager.ConnectionStrings["DB"].ToString()))
{
Table1 tab = new Table1
{
FName = item.FName,
LName = item.LName,
Number = item.Number,
};
db1.Table1.InsertAllOnSubmit(tab);
db1.SubmitChanges();
}
}
}
I can’t compile it. It throws this error at line ‘db1.Table1.InsertAllOnSubmit(tab)‘:-
‘System.Data.Linq.Table.InsertAllOnSubmit(System.Collections.Generic.IEnumerable)’
cannot be inferred from the usage. Try specifying the type arguments
explicitly.
Your code has some flaws.
You seem to read one Table1 (assuming the id is unique) but you are treating it like a collection
Quick try since you anyway add only one table1 at a time: Replace
by
If your ID is not unique try:
The rest of the code can stay the same (but still replace the InsertAllOnSubmit)
Update
You can simplify bigtime:
if you are 100% sure your id will always match use .Single() instead of .SingleOrDefault(). Single will throw an exception if no result matches. SingleOrDefault returns NULL in this case.