Question

So i am having a real issue with this. I wan add a foreign key to a row i am adding to a database. I have all my references setup so they all map up perfectly fine.

The issue is that i want to add the key without running the query until all rows are submitted.

example tables

**FirstNameTable**    **LastNameTable**        **People-Table**
Id | Value            Id | Value               Id | FirstNameID | LastNameID 
----------------      ---------------          ------------------------------
1  | Jeff             1  | jones               1  | 1           | 3          
2  | Joe              2  | Richards            2  | 2           | 1          
3  | John             3  | bobson              3  | 3           | 2          

So Table3 has 3 foreign keys (FirstNameId links to FirstNameTable, LastNameId links to LastNameTableand ParentId links to People-Table). For the sake of this example lets just say that there will never be a person that has the same first and last name.

I want to add a new entry for table 3 but i want it to either use an existing entry if it is there or create a new one.

Now doing

People-Tabletb3 = new People-Table()
{
    FirstNameTable = new FirstNameTable(){ Value = Jeff};
    LastNameTable= new LastNameTable(){ Value = jones};
}

Will always create a new entry in my other two tables. Doing the following for each row in each table

if ((from u in dc.Users where u.Name == name select u).Count() > 0)
    // just grab the id
else
    // make it then grab the id

Isn't really an option because you are then doing more queries and slowing down the upload.

So my question is how do i create a new People-Table row using LINQ that will use an existing row for the first and last name or create a new one if it doesn't exist. Without doing the if-else stuff.

Was it helpful?

Solution

  1. Create a list of all the distinct names in your list of entries that you're trying to insert.
  2. Create a query that pulls all of the values from the Users table, whose names are found in the list you just created. Put these values into a dictionary, keyed by their name.
  3. Loop through the entries you want to insert, and for each of those, either associate them with a value from the dictionary you created, or create a new value and add it to the dictionary.

This should do what you're asking, for any number of new entries, in two round-trips total.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top