Wednesday, October 3, 2007

Linq to Sql - Entities As Static Resources?

Here is what I would like to have:


public class WorldCountries
{
public static Country China = new Country(new Guid("6d4b5217-6fe6-11dc-8314-0800200c9a66"), "China");
public static Country Mexico = new Country(new Guid("6d4b5219-6fe6-11dc-8314-0800200c9a66"), "Mexico");
public static Country UnitedStates = new Country(new Guid("6d4b521a-6fe6-11dc-8314-0800200c9a66"), "United States");
 



public static List Countries
{
get
{
List defaultValues = new List();
defaultValues.Add(China);
defaultValues.Add(Mexico);
defaultValues.Add(UnitedStates);
return defaultValues;
}
}
}

public class UnitedStates_States
{
public static State Alabama = new State(new Guid("4f4588b0-6fe6-11dc-8314-0800200c9a66"), WorldCountries.UnitedStates, "AL", "Alabama");
public static State Alaska = new State(new Guid("4f4588b1-6fe6-11dc-8314-0800200c9a66"), WorldCountries.UnitedStates, "AK", "Alaska");
public static State Arizona = new State(new Guid("4f4588b3-6fe6-11dc-8314-0800200c9a66"), WorldCountries.UnitedStates, "AZ", "Arizona");
public static State Arkansas = new State(new Guid("4f4588b4-6fe6-11dc-8314-0800200c9a66"), WorldCountries.UnitedStates, "AR", "Arkansas");
public static State California = new State(new Guid("4f4588b5-6fe6-11dc-8314-0800200c9a66"), WorldCountries.UnitedStates, "CA", "California");
 



public static List States
{
get
{
List defaultValues = new List();
defaultValues.Add(Alabama);
defaultValues.Add(Alaska);
defaultValues.Add(Arizona);
defaultValues.Add(Arkansas);
defaultValues.Add(California);

return defaultValues;
}
}
}
  

Then I can CreateDatabase() on my data context and make a call to a function like this:


public void AddAllDefaultValues()
{
// Add world countries first because all relations depend on them
AddNewValues(_DataContext.Countries, WorldCountries.Countries);
// Add states by country
AddNewValues(_DataContext.States, UnitedStates_States.States);
}
 


public void AddNewValues(Table Table, List Values)
where TEntity : class
{
if (Table.Context != _DataContext)
{
throw new Exception("Table must be in the same context as the DefaultValueManager");
}
var currentValues = from values in Table
select values;
List currentValuesList = currentValues.ToList();
IEnumerable valuesToAdd = Values.Except(currentValuesList);

try
{
Table.AddAll(valuesToAdd);
_DataContext.SubmitChanges();
}
catch (InvalidOperationException ioe)
{
throw ioe;
}
}
  


So far so good. Everything seems to be working, unit tests verify that my database is created, check that the default values have indeed been populated and are happy.

Now I get into my application and I want to create a new State entity, so I new up the object, call add on my data context, submit changes and... error... huh?


"System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_dbo.Countries'. Cannot insert duplicate key in object 'dbo.Countries'."
  

Here some example code (copied from failing unit test):


State expected = new State(new Guid("694df2b2-7002-11dc-8314-0800200c9a66"), WorldCountries.UnitedStates, "TS", "Test State");

_DataContext.States.Add(expected);
_DataContext.SubmitChanges();
  


The data context is stashed in a static variable in the test class, passed to the manager class that does the DatabaseCreate and AddAllDefaultValues calls.

The same data context is then used in the tests to perform the same operation against the same objects... what's going on?

Here is how I can get around this, but it's far from ideal and renders all the static elements useless:


var countries = from c in _DataContext.Countries
where c.CountryName == "United States"
select c;
Country country = countries.SingleOrDefault();

State expected = new State(new Guid("694df2b2-7002-11dc-8314-0800200c9a66"), country, "TS", "Test State");

_DataContext.States.Add(expected);
_DataContext.SubmitChanges();
  


A comparison between the static entities does reveal some differences but I haven't (yet) identified the key item(s) but the net result is this statement attempting to execute and re-add the country which is what causes the Primary Key constraint to break.


INSERT INTO [dbo].[Countries]([CountryId], [CountryName]) VALUES (@p0, @p1)
-- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [6d4b521a-6fe6-11dc-8314-0800200c9a66]
-- @p1: Input String (Size = 13; Prec = 0; Scale = 0) [United States]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.20706.1
  

[Copied from output ala Kris Vandermotten]


The only idea that I have at the moment (untested) is to expose each item instead as a static property and doing a lookup and return on demand but it seems to me that there should be a way to enable this with some state flag modifications to the static entities or something.

24 comments:

Anonymous said...

I have thought and have removed the idea

Anonymous said...

Do You interesting of [b]Female use of Viagra[/b]? You can find below...
[size=10]>>>[url=http://listita.info/go.php?sid=1][b]Female use of Viagra[/b][/url]<<<[/size]

[URL=http://imgwebsearch.com/30269/link/buy%20viagra/1_valentine3.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/1_valentine3.png[/IMG][/URL]
[URL=http://imgwebsearch.com/30269/link/buy%20viagra/3_headsex1.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/3_headsex1.png[/IMG][/URL]
[b]Bonus Policy[/b]
Order 3 or more products and get free Regular Airmail shipping!
Free Regular Airmail shipping for orders starting with $200.00!

Free insurance (guaranteed reshipment if delivery failed) for orders starting with $300.00!
[b]Description[/b]

Generic Viagra (sildenafil citrate; brand names include: Aphrodil / Edegra / Erasmo / Penegra / Revatio / Supra / Zwagra) is an effective treatment for erectile dysfunction regardless of the cause or duration of the problem or the age of the patient.
Sildenafil Citrate is the active ingredient used to treat erectile dysfunction (impotence) in men. It can help men who have erectile dysfunction get and sustain an erection when they are sexually excited.
Generic Viagra is manufactured in accordance with World Health Organization standards and guidelines (WHO-GMP). Also [url=http://twitter.com/jetlyca]q Buy Viagra Online[/url] you can find on our sites.
Generic [url=http://viagra.olistupa.ru]Viagra Super Active[/url] is made with thorough reverse engineering for the sildenafil citrate molecule - a totally different process of making sildenafil and its reaction. That is why it takes effect in 15 minutes compared to other drugs which take 30-40 minutes to take effect.
[b]viagra cost
100 milligram phyzer viagra
expiration date of viagra patent
viagra beer
viagra cataracts
generic prescription drugs
Viagra Patent Canada
[/b]
Even in the most sexually liberated and self-satisfied of nations, many people still yearn to burn more, to feel ready for bedding no matter what the clock says and to desire their partner of 23 years as much as they did when their love was brand new.
The market is saturated with books on how to revive a flagging libido or spice up monotonous sex, and sex therapists say “lack of desire” is one of the most common complaints they hear from patients, particularly women.

Anonymous said...

generic viagra buy viagra online 25mg - buy viagra online overnight delivery

Anonymous said...

buy soma 350mg soma online - soma usa

Anonymous said...

order soma order soma overnight - soma 79984 bra

Anonymous said...

cialis online generic cialis tadalafil 40 mg - cialis 8 cpr

Anonymous said...

buy tramadol no rx tramadol 50mg capsules for dogs - tramadol kali 083

Anonymous said...

tramadol online buy tramadol online cod only - buy tramadol online without rx

Anonymous said...

cialis price generic cialis rx - cialis online legale

Anonymous said...

order alprazolam no prescription xanax xr 1 mg twice a day - xanax and zoloft overdose

Anonymous said...

xanax online is it illegal to buy xanax online from the us - xanax online legit

Anonymous said...

tramadol online overnight safest place buy tramadol online - tramadol withdrawal long does last

Anonymous said...

buy carisoprodol online no prescription carisoprodol 446 - carisoprodol online no prescription

Anonymous said...

carisoprodol 350 mg carisoprodol 350 high - soma or carisoprodol

Anonymous said...

buy carisoprodol carisoprodol oral side effects - carisoprodol 350 mg xanax

Anonymous said...

http://www.integrativeonc.org/adminsio/buyklonopinonline/#9183 klonopin benzo - 2mg generic klonopin

Anonymous said...

buy tramadol online legit online pharmacy tramadol - tramadol 100 mg lp

Anonymous said...

buy klonopin online klonopin side effects anxiety - generic klonopin just good

Anonymous said...

buy tramadol next day tramadol overnight shipping cod - buy tramadol cheap online no prescription

Anonymous said...

buy tramadol tramadol withdrawal management - tramadol hcl generic ultram

Anonymous said...

buy klonopin online klonopin teva 833 - klonopin side effects leg pain

Anonymous said...

carisoprodol 350 mg soma carisoprodol tablets side effects - carisoprodol 50mg

Anonymous said...

carisoprodol 350 mg carisoprodol class - carisoprodol online cheap

Anonymous said...

http://southcarolinaaccidentattorney.com/#31694 buy carisoprodol online - medicine carisoprodol 350 mg