我有一段涉及多个插入的代码,但是需要在完成向其他表中的插入之前执行Submitchanges方法,以便我可以获取一个ID。我一直在互联网上搜索,找不到如何在linq to sql中创建事务。我已在要进行交易的代码中添加了注释。
var created = false;
try
{
var newCharacter = new Character();
newCharacter.characterName = chracterName;
newCharacter.characterLevel = 1;
newCharacter.characterExperience = 0;
newCharacter.userUsername = userUsername;
newCharacter.characterClassID = ccslst[0].characterClassID;
//Open transaction
ydc.Characters.InsertOnSubmit(newCharacter);
ydc.SubmitChanges();
foreach (var ccs in ccslst)
{
var cs = new CharacterStat();
cs.statId = ccs.statID;
cs.statValue = ccs.statValue;
cs.characterID = newCharacter.characterID;
ydc.CharacterStats.InsertOnSubmit(cs);
}
var ccblst = ydc.ClassBodies.Where(cb => cb.characterClassID == newCharacter.characterClassID);
foreach (var ccb in ccblst)
{
var charBody = new CharacterBody();
charBody.bodyId = ccb.bodyId;
charBody.bodyPartId = ccb.bodyPartId;
charBody.characterID = newCharacter.characterID;
ydc.CharacterBodies.InsertOnSubmit(charBody);
}
ydc.SubmitChanges();
created = true;
//Commit transaction
}
catch (Exception ex)
{
created = false;
//transaction Rollback;
}
return created;
编辑:忘记提及ydc是我的datacontext