Bite my bytes

What I learn by day I blog at night - A blog from Microsoft Consultant working from Ljubljana, Slovenia

  Home :: Contact :: Syndication  
  999 Posts :: 7691 Comments :: 235 Trackbacks

Search

Most popular posts

Categories

My Projects

Archives

Stuff


Copyright © by David Vidmar
 
Contact me!
 
LinkedIn Profile
 
 
 

I ran into an issue with my latest project at work that uses LINQ. I was upserting some entities and when I encountered a duplicate, I queried the database, but not the pending inserts of my DataContext, so my import failed with "duplicate primary key" type of error.

It turns out it's fairly easy to query those pending inserts too.

Lets have a DataContext and do an insert of a new Color entity:

DataContext dc = new DataContext();
dc.Colors.InsertOnSubmit(new Color() { Code = "F0F8FF", Name = "AliceBlue" });
 
Since we didn't do dc.SubmitChanges(), the following query returns nothing:
 
var r = from c in dc.Colors where c.Code = "F0F8FF" select c;

Enter GetChangeSet(). Let's count inserts:

int allPendingInserts = dc.GetChangeSet().Inserts.Count();
 
But we can have pending inserts of different types/tables. Let's just count pending colors:
 
int colorsPendingInserts = dc.GetChangeSet().Inserts.OfType(Color).Count();
 
And now we are not very far from querying inserted records:
 
IEnumerable<Color> insertedColors = dc.GetChangeSet().Inserts.OfType<Color>();

Console.WriteLine(
   
string.Format(
        "Q: Is color #F0F8FF already pending insert?\n"
+
        "A: {0}"
,
       
(from q in insertedColors where q.Code == "F0F8FF" select q).Count > 0));
 
Did I mention I really like LINQ? (except when crossing WCF, of course)
Posted on Tuesday, June 17, 2008 12:32 PM | Filed under: Developement |
Comments have been closed on this topic.