.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

DuplicateKeyException on datacontext.SubmitChanges()

Posted By:      Posted Date: August 21, 2010    Points: 0   Category :ASP.Net

I have a global variable for datacontext object, which I use for two different methods first for deleting a set of records and then inserting a set of records. The delete works fine but while insert, it throws the above exception when SubmitChanges is called.


Any help is appreciated........

Thanx in Advance. 

View Complete Post

More Related Resource Links

The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced. You must



This is frustrating, and I don't know how to solve it.

I have a strange problem. I am adding a LinqDatasource object, and set the context:

        protected void LinqDataSource_ContextCreating(object sender, LinqDataSourceContextEventArgs e)
            e.ObjectInstance = new KaruselaDataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

Then I get this error:
The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Linq, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'.


On web.config I already have this:
<add assembly="System.Data.Linq, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>

NOTE: The datacontext is in a different project (DLL proect) where I added a refernce to System.Data.Linq.

is there another way adding a refernce to a web project? or only though teh web.config?


Can't find my datacontext in custom fieldtemplate


I am trying to implement sjnaughton's ChildrenGrid (a Dynamic Data FieldTemplate that displays foreign key child rows...) ... I am having problems at runtime, though. The following call in my code:

table = GridDataSource.GetTable();

Is failing with the error: System.Web.HttpException: Could not load type 'ModelDataContext'.

ModelDataContext is indeed the name of my .dbml file... I can declare a local instance of this class and that works fine,something like

var t = new ModelDataContext();

No exception. And the rest of my Dynamic Data classes work fine. I am trying to get the table from a griddatasource, and I know I am setting the context properly on this line

GridDataSource.ContextTypeName = metaChildColumn.ChildTable.DataContextType.Name;

I have debugged and the string is set to "ModelDataContext" just fine. I tried appending the full namespace for my context, like "MyApp.App_Code.ModelDataContext", but then I get an ambiguous assembly name... but I only have one ModelDAtaContext... I cleaned out my project, deleted ASP.NET temp folder files, etc. Still, no dice. Here is the code in full context:

using System;
using System.Data;
using System.Configuration;
using System.

Sys.Data.DataContext.saveChanges method doesn't send update to server after DataServiceException ex

Hello,I have a page with a simple form that updates a single record in a table in my database.The database is accessed via WCF Data Services. To load and save data from/to the server, I usethe Sys.Data.DataContext object provided by the ASP.NET AJAX library. When the "save" button on theform is clicked, I use the saveChanges method of the Sys.Data.DataContext object to send all changes to the server.Also, at the server side, I use an interceptor that checks the "Price" fields of the record, and throws a DataServiceException exception when the contents of the field is a negative number.Both the JavaScript and the interceptor (in C#) are copied below.Here is the interesting thing:When I enter a negative price in the form, the interceptor throws the exception and my form shows an error message. Good.However, if I then make one of the other fields in the form a bit shorter (for example from "abcd" to "abc"),the saveChanges method doesn't send the data to the server. But it does call the success callback that I passed in to saveChanges, creating the impressionthat the data has been saved. This happens while the Price field is still negative. I used Fiddler to make sure thatno message is sent to the server. Also, the interceptor doesn't get executed.The weird thing is that if I make one of the fields a bit longer instead (for example &q

Missing DataContext! Was working fine, now it's hosed

So I have a web application, set up for .NET 4.0 ... I had a robust LINQ TO SQL Classes object, and it was running just fine. But I needed to make a schema change so I altered my database. No problem. Then I went into my .dbml file and deleted the table I had been working on. Then I re-added the table by dragging it from the server explorer. However, now my code is throwing a number of errors, all saying they can't find my DataContext, called ModelDataContext. I hadn't changed any other app code, so I am really confused!Error 3 The type or namespace name 'ModelDataContext' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Ed\Projects\NBAdminPanel\NBAdminPanel\WebApplication1\DynamicData\CustomPages\Accounts\Edit.aspx.cs 49 29 NBAdminPanel The type or namespace name 'ModelDataContext' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Ed\Projects\NBAdminPanel\NBAdminPanel\WebApplication1\DynamicData\CustomPages\Accounts\Edit.aspx.cs 49 29 NBAdminPanelSo basically my app no longer knows about the class generated from this DBML file. I have tried recreating it by deleting the old one and readding objects to the new one, no dice. I am at my wits end; hoping I don't have to junk the project and start a new one! My DBML file is still in MyProject.App_Code. 

Changing datacontext gives binding errors

On the change of the datacontext (of a user control), I check the type of the datacontext. If required (in my case, the datacontext is of a specific type), I want to change the datacontext. As soon as I change the datacontext, the DataContext property is correctly updated. However, I still get binding errors that "Property 'x' is not found on type 'y'", where 'y' is the old datacontext type. Is there any specific steps I have to take to successfully update the datacontext (and the bindings) to the new datacontext object?Geert van Horrik - CatenaLogic Visit my blog: http://blog.catenalogic.com Looking for a way to deploy your updates to all your clients? Try Updater!

How we Update DataContext's Table Implicitly in Linq using .Net 3.5..?

Hi All.. My problem is i am working on Linq,as we know to use any table in linq we have to drag and drop it on our datacontext's Designer File,and at run time we got its value,till here no any problem,main point is if any changes in respective data source's schema has made ,then on datacontext we will not get that changes,for it we have to change this datacontext manually by by again drag and drop,it will not happen implicitly when this changes has been made on the data source. so please tell me how i solve this problem so that datacontext change implicitly without any over head  using .net 3.5 . 

Cannot set DataContext to a Class through XAML

Hi, I understand this has been answered several times as I browse this forum, however I can't get the various implementation examples to work within my code - i think i need help. Here's a perfectly working code: namespace TestStuff { public partial class Window1 : Window { class woot { int _bind = 50; public int Bind { get { return _bind; } set { _bind = value; } } } woot WOOT = new woot(); public Window1() { InitializeComponent(); mygrid.DataContext = WOOT; } } }   <Window x:Class="TestStuff.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid Name="mygrid"> <Label Content="{Binding Path=Bind}"/> </Grid> </Window> What's the simplest way to set the DataContext of "myGrid" to WOOT, through XAML instead of using C#? Something like: <Grid DataContext="WOOT"> There are so many replies out there involving relativesource, objectdataprovider, dependency properties... however for some reason, I can't get any of them to work properly. I need to set the datacontext to the grid and not the window, since different grid

How to bind datagrid columns to external (main) datacontext?



I have a datagrid and his columns binds well to its collection data. But when I add a new data column (ie. DataGridTextColumn or DataGridComboBoxColumn) and Bind to the main Data Context of window the data are missing (dont show)

In this sample, The last two columns of DataGrid dont bind to the main data.

<Window x:Class="MainWindow"





Binding Question How does one set datacontext to same class in XAML?


I have a usercontrol with one button in it.  I want to set the text via a property getter setter using the INotifyPropertyChanged interface in code behind.  I can get it to work if I set the DATACONTEXT in code behind in the CTOR like this : DataContext = this;  Everything works perfect. 

But here's the problem.  If I try to do this in xaml by defining an XMLNS which points to the folder this usercontrol is in, and then attempt to reference it as a resouce like this <local:XXXXXX  <-------The XXXX which is the class name of this control can't be found?  Is that wierd?  Can't a resource be itself?  So that I can set the Datacontext in the XAML instead of code behind?  I've tried to bind to relative source self, but cannot set the property (Event when I attempted to created a dependency property).....  Just wondering how one sets up Datacontext to the same class? 


DataContext scopes on bound ComboBox



I'm just learning WPF and finding binding almost so easy that it's starting to confuse me. I've got a zip codes ComboBox inside of a Grid that has a DataContext set to a custom object. I set up a binding between my ComboBox's SelectedValue and my object's zip code ID. In my code behind I bind the ComboBox to an ADO.NET DataView containing the zip code ID, the zip code, and the city name. So I also set up a DataTemplate for my ComboBox items that will display the zip code and city. So here's my xaml:

  SelectedValuePath="ZipCodeID" Grid.Column="

Combobox Set Selected Item from DataContext


i have a listview that houses a gridview .

I have the first column as combobox column defined in the datatemplated of the firstcolumn

I have set the Datacontext of the listview to a datatable having the folowing columns

Code,Name ,age.

i am able to set the binding for the 2 textboxes .

Here , the Code combobox has a set of allowed values that i am fetching from the Db as a datatable again .

now my requirement here is

1) to set the Itemsource of the combobox to the datatable. so that it has all the allowed codevalues.

2) the comboxbox for that particular row must show the (Selecteditem) corresponding value from the dataset of the Listview.

I am unable to set it itemsource directly because its in the datatemplate.

and i am unable to set binding to the selected item too.

Any help?

I tried setting the SelectedValue="{Binding Path=Code}" And its successfully getting the value.

But because i am unable to set the itemsource of it . i have written a Loaded event of the combobox and there i am settin the itemsource of it.

Hence Because of this. The selected value of the combobox is gettin overridden and is reset to null wheni am setting the itemsource.

i just need a way to set the itemsource first and then the binding to fire.


LINQ to SQL - SubmitChanges not working


I have an XML string in memory, which I want to write to my database. I'm using LINQ

But SubmitChanges() isn't working. Everything works fine up to that point, and all the values are correct when I debug. The database values just aren't updated.


        //pare down xml to contain locations only
        //using LINQ
        XElement resultData = XElement.Parse(xmlResult);  //xmlResult is the string containing the XML
        var locationsXmlData = from lc in resultData.Descendants("location")
                        select lc;

        //for each location, write data to database
        LocationDataContext locationData = new LocationDataContext();

        foreach (var locationXmlElement in locationsXmlData)  
            XElement xmlId = locationXmlElement.Element("locationid");
            //check if id/key already exists for this location
            var queryExists = from dbRow in locationData.locations  //locations is db table name
                              where dbRow.locationid == (

LINQ to SQL SubmitChanges() not working sometimes


I was trying to delete records from database and sometimes on production, the SubmitChanges() goes through and updates the associated entities yet the data does not gets deleted in the database. This is happening only in production and I could not replicate the same on stage or on my local machine. Now the table in which I am performing the delete transaction does have primary keys.

Any suggestions ??

My code reads like

private void DataPortal_Delete(EntityScenarioCriteria criteria)

Inserting an anonymous type using a Linq DataContext - fail


Hi All,

For the following code block:

using (PatientTypesDataContext context = new PatientTypesDataContext())
                var patientTypeRecord = new
                    RequestId = 88,    //test values all
                    MedicalRecordNumber = 1,
                    AccountNumber = 1,
                    CSN = true,
                    PatientType = 1,
                    CustomPatientType = 1,

SPMetal: Using Linq to SharePoint Datacontext to Insert Page


I am trying to insert a Page (on a Publishing Site) in SharePoint 2010 using the generated SPMetal classes.

Here is the code that I am using to insert a page:

using (var dataContext = new MySharePointSite1L2spDataContext("http://localhost"))
  var pages = dataContext.GetList<Page>("Pages");
  Page page = new Page();
  page.Title = "New Page";
  page.Name = "Page.aspx";    
  page.Path = "/Pages";

The code results in an NullReferenceException with the details "Object reference not set to an instance of an object."

Stack Trace:
   at Microsoft.SharePoint.Linq.EntityTracker.AddFile(EntityRef eref)
   at Microsoft.SharePoint.Linq.EntityTracker.SubmitNewEntity(NewEntityRef newEref, Stack`1 visited)
   at Microsoft.SharePoint.Linq.EntityTra

DataContext not set when trying to use Presenter


I am very new when it comes to using Presenters but am trying my best, I was able to use so that I could set different user controls onto a tab control using one function however I am on a new project and the same doesn't work when using a frame, can anyone help point out the issue.

Without putting in all the different presenter code my issue actually lies within the following two lines of code where I try to set a user control in the frame 'frmContent':

public void LoadView<T>(PresenterBase<T> presenter) 
      frmContent.DataContext = presenter;      
      frmContent.Content = presenter.View;
Basically a user control is the presenter in this case called frmDetails but the DataContext of it is not set in the code above. When I used the same code for my tabcontrol previously this worked fine.  Is it something to do with Frames?

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend