tags:

views:

42

answers:

1

I get this error when insert a new album:

{System.Data.SqlClient.SqlException: 
INSERT statement conflicted with COLUMN FOREIGN KEY 
constraint 'FK_ChannelAlbum_Group'. 
The conflict occurred in database 'Stamper', table 'Channel', column 'ID'.

I don't know what is going on because sometime I insert the new album to the context the error will occur but Album table has no Channel ID columns only Album_Channel table. This insert does not influence the album_channel and channel table at all. Why is there a conflict.

I realized that after I have created the new album after that i try inserting a album_channel data I have an error so I stop debugger and try to fix the problem. Once i have work that out, I go an insert a new album once more but it gives me this error always. So I close my visual studio and reopen it in order to work.....

I am not sure is it a good way of having singleton style of creating the context e.g.

I have write a context as class and this context only created once, to prevent it to create too many times.

A: 

Hard to answer without a diagram. It looks like you have a foreign key in the table you're inserting which is not a valid primary key in the table it is referencing. If you don't believe you have one, then you could try checking your relationships and possibly regenerating your L2S entities. Maybe even try to insert into that table manually and see if you get the same error.

Context wrapped in a singleton is a bad idea for web applications as it isn't thread safe. You could look into the 'unit of work' pattern or try caching the context instance.

Sergey
I have no idea the creation of the context class will or will not affecting the speed of the code. So if I create the context everytime I execute the query it will become very inefficient..
It isn't a performance hit and a new data context per unit-of-work is the suggested behavior. So, typically, you would have a repository class with each member member creating their own instance of the data context. However, if you're going to be using multiple repositories and start passing entities around you'll have to detach them from original context and reattach them to the new one. Which i always found to be a big issue. This is where a cached context per unit-of-work works great since you repositories would use the same context instance as long as they're the same 'unit'.
Sergey
Another thing you could do is create a threat-static singleton. That is, a singleton object with your static instance being thread-static. This is by far the easiest approach to this problem and something i use myself. By the way, to create a thread-static variable you just have to put [ThreaStatic] attribute on your static variable.
Sergey