Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Friday, April 27, 2012

On a different note: today I learned something very interesting about LINQ To SQL (a C# .NET framework).

Given a database table

In some code at work I wanted to first run through some data extractions, calculate final statistics and then populate this table. But before the insert, I want to find all rows that currently exist that match the same Date and delete.

So what I did was as I create each new row to insert, I make a new object of that Table's type: Daily_Total.

Daily_Total dt = new Daily_Total{ ...,...,...,...};

Then I add it to a generic list of type Daily_Total

List<Daily_Total> dailyList = new List<Daily_Total>();

...(gathering data)...

dailyList.Add(dt); (repeated for every new row)

Once this is all collected, I then do a query on the table to gather those items to delete and do the deletion like such:

dbContext.Daily_Totals.DeleteAllOnSubmit(toDelete);

dbContext.SubmitChanges();

And then the weirdest thing happens that I haven't experienced yet. Not only do the rows I want to delete get deleted, but the generic list of objects of that tables type are INSERTED. No InsertAllOnSubmit(dailyList) or anything. Just simply having a generic collection of those new rows gets itself submitted.

This took me a bit to figure out why my code was throwing a "Cannot insert entry that already exists" exception. I'm going to have to research why this happens. It seems incorrect to me since I may not want a temporary, local version of my new rows to be submitted yet. Of course, I could also be doing something wrong.