Domanda

Quindi, sto cercando di fare una transazione con LINQ to SQL. Ho letto che se uso SubmitChanges(), creerebbe una transazione ed eseguire tutto e in caso di tutto ciò eccezione sarebbe il rollback. Ho bisogno di usare SubmitChanges() multipla? Sto usando qualcosa di simile a questo codice e non funziona perché non sta salvando i dati sul primo tavolo .. (ho bisogno di ID per la tabella dei bambini).

Se io uso un altro diritto SubmitChanges() dopo il primo InsertOnSubmit non è vero perde l'idea di una transazione?

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();
È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top