ASP.NET 4.0 C#,Linq to SQL:我要求一旦创建了新行,我需要将标识值写回同一行中的另一个字段。
我尝试了这个,但它不起作用(没有找到或更改行):
//newRow created and fields populated here
dc.Table.InsertOnSubmit(newRow);
dc.SubmitChanges();
newRow.Field = newRow.PriKey;
dc.SubmitChanges();
我也尝试将行读入新变量并更新但同样的错误:
//newRow created and fields populated here
dc.Table.InsertOnSubmit(newRow);
dc.SubmitChanges();
row2 = (from r in dc.Table where r.PriKey = newRow.PriKey select r).FirstOrDefault();
row2.Field = newRow.PriKey;
dc.SubmitChanges();
我想我可以通过创建和执行自己的SQL命令轻松完成此操作,但有更简单的方法吗?
编辑:事务包装在事务中是否会产生影响?
using (CMSDataContext dc = new CMSDataContext(Config.ConnString))
{
dc.Connection.Open();
dc.Transaction = dc.Connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
答案 0 :(得分:1)
这似乎不是LINQ2SQL的限制,在LINQPad中运行以下似乎工作正常。您是否尝试在调试器中单步执行代码?或者您可以发布您的真实代码来检查其他问题吗?
create table data
(
ID int not null identity primary key,
Value varchar(16) not null,
PKStore int null
)
var newRow = new Data{Value = "MyVal"};
Data.InsertOnSubmit(newRow);
SubmitChanges();
newRow.PKStore = newRow.ID;
SubmitChanges();
Data.Dump(); //LINQPad Method
输出
答案 1 :(得分:-1)
尝试排序并从列表中选择顶行
dc.Table.InsertOnSubmit(newRow);
dc.SubmitChanges();
row2 = (from r in dc.Table order by r.PriKey desecnding select r).FirstOrDefault();
row2.Field = row2.PriKey;
dc.SubmitChanges();