문제

So, I'm trying to make a transaction with LINQ to SQL. I read that if I use SubmitChanges(), it would create a transaction and execute everything and in case of an exception everything would be rolled back. Do I need to use MULTIPLE SubmitChanges()? I'm using something like this code and it isn't working because it isn't saving any data on the first table.. (I need it's ID for the children table).

If I do use another SubmitChanges() right after the first InsertOnSubmit doesn't it lose the idea of a transaction?

myDataContext db = new myDataContext();

Process openProcess = new Process();

openProcess.Creation = DateTime.Now;
openProcess.Number = pNumber;

//Set to insert

db.Process.InsertOnSubmit(openProcess);

Product product = new Product();

product.Code = pCode;
product.Name = pName;
product.Process_Id = openProcess.Id;

//Submit all changes at once?

db.SubmitChanges();
도움이 되었습니까?

해결책

The problem is, that the ID of your process is set when the changes are submitted to the database. Because you submit the changes after the line where you assign the process id to the product (product.Process_Id = openProcess.Id;).

The correct way to do this would be to correctly setup your database with a foreign key from PRODUCT to PROCESS and use the navigation property Process on Product to assign the process to the product.

The code would look like this:

myDataContext db = new myDataContext();

Process openProcess = new Process();

openProcess.Creation = DateTime.Now;
openProcess.Number = pNumber;

Product product = new Product();

product.Code = pCode;
product.Name = pName;
product.Process = openProcess;

db.Product.InsertOnSubmit(product);
db.SubmitChanges();

Because Process is a navigation property of Product, you don't need to insert the Process. It will be inserted automatically, because you insert the "parent" - the Product.

다른 팁

You can make the whole thing transaciotnal using a TransactionScope e.g.

using (TransactionScope scope = new TransactionScope())
{
myDataContext db = new myDataContext();

Process openProcess = new Process();

openProcess.Creation = DateTime.Now;
openProcess.Number = pNumber;



db.Process.InsertOnSubmit(openProcess);
db.SubmitChanges();
//openProcess.Id will be populated

Product product = new Product();

product.Code = pCode;
product.Name = pName;
product.Process_Id = openProcess.Id;    

db.Products.InsertOnSubmit(product); // I assume you missed this step in your example
db.SubmitChanges();

scope.Complete()
}

If an exception is thrown before scope.Complete() is called then the whole thing will be rolled back.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top