TLDR Summary
I'm having a few issues with ASP.net MVC's InsertOnSubmit() function. How do you build and insert new objects into the database without running into key constraints?
Steps to Reproduce
I've gone ahead and created a simple demonstration of the 3-or-so major problems I've been having and maybe someone can help me out here.
- Create a new ASP.net MVC 2 project.
- Create two tables- Experiments and Results with a One-To-Many relationship (shown below).
- Create a new action within the Home controller called "RunExperiment".
- Create a basic linq-to-sql data context.
- Have RunExperiment generate a new experiment and results, and insert them into the database via the new data context.
This process falls apart quickly since there's some magic that needs to happen to prevent duplicate primary keys and to ensure that the dependencies stay intact.
Now take a look at my example "RunExperiment" function:
public ActionResult RunExperiment(string Title, string Scientist)
{
RepositoryDataContext RDC = new RepositoryDataContext();
// Generate the experiment
Experiment thisExperiment = new Experiment();
thisExperiment.experimentTitle = Title;
thisExperiment.experimentScientist = Scientist;
// Perform some work.
System.Threading.Thread.Sleep(500);
// Attempt to insert the experiment.
// Works once, fails subsequently due to duplicate primary key.
RDC.Experiments.InsertOnSubmit(thisExperiment);
RDC.SubmitChanges();
for (int i = 0; i < 5; i++)
{
Result thisResult = new Result();
thisResult.resultDate = DateTime.Now;
thisResult.resultTemp = i;
thisResult.Experiment = thisExperiment;
RDC.Results.InsertOnSubmit(thisResult);
RDC.SubmitChanges();
}
return View("Index");
}
Any thoughts? I know this is basic stuff, but I'm trying to work away from just copying the Nerd Dinner pattern but I'm getting these errors.
Thanks!