C# - How To Insert A Copy Of A Row (with A New Identity) Using LINQ To SQL
Feb 16, 2011
I have a number of tables that together make up a "Test" that somebody can take. There are multiple types (scripts) of Test a person can take. I'm working on an Edit function that will allow somebody to edit the Test Questions. I want these edited questions to show up on all new Tests of that type, but still show the old questions when viewing past test scores.
To do this each "Test" has a TestId auto-increment identity (along with its name). When a test is edited I want to make a copy of the test with a new TestId and present the questions for editing.
So what is the best way to make the copy and insert it into my table using LINQ to SQL? This:
DataContext db = new DataContext(ConnectionString);
//Copy old test into identical new test but with a different script ID
var oldScript = db.TestScripts.Single(ds => ds.TestScriptId == oldScriptID);
var newScript = oldScript;
db.TestScripts.InsertOnSubmit(newScript);
db.SubmitChanges();
of course tells me that I Cannot add an entity that already exists.
Is the only way to do this to go through every column in the TestScript and copy it manually, then insert it, and the database will give it a new Id?
View 3 Replies
Similar Messages:
Aug 16, 2010
DataClassesDataContext db = new DataClassesDataContext();
test cust = new test()
{
ID = I need identity key
};
How to get identity key?
View 1 Replies
Mar 9, 2011
I have a registration page that must contain a user id label. When a user tries to register, the label on the page should show the identity value for the registration before completion. How to do this?
View 1 Replies
Jun 16, 2010
Following the MVC1 vers of Nerddinner, but using 2010 and MVC2. Never seen this error. Looked in controller, model, view. Where does MVC pass the identity value, and how to stop it? I have never had to set IDENTITY_INSERT in any app before.
View 2 Replies
Jan 21, 2010
I have been searching on here for many hours and read many posts but for some reason I am being slow and cannot figure this out. I am writing a record and need to get the identity field back. I have tried many combinations based on what I have read but the below code is where I am sitting at now. it has appdatasource.ExecuteScalar() underlined and the error says 'ExecuteScalar' is not a member of 'System.Web.UI.WebControls.SQLDataSource'. I would be very grateful if someone could point out what I am missing to get this to work.
Protected Sub SubmitApp_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitApp.Click
Dim appdatasource As New SqlDataSource
appdatasource.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString1").ToString
appdatasource.InsertCommandType = SqlDataSourceCommandType.Text
appdatasource.InsertCommand = "INSERT INTO APPLICATION (FirstName,MiddleName,LastName,AcceptTerms,IPv4Address,DateInserted) VALUES (@FirstName,@MiddleName,@LastName,@IPv4Address,@DateInserted);select @@SCOPE_IDENTITY"
appdatasource.InsertParameters.Add("FirstName", fname.Text)
appdatasource.InsertParameters.Add("MiddleName", minit.Text)
appdatasource.InsertParameters.Add("LastName", lname.Text)
appdatasource.InsertParameters.Add("DateInserted", DateTime.Now())
appdatasource.InsertParameters.Add("IPv4Address", Request.UserHostAddress.ToString)
Dim appid As Integer = appdatasource.ExecuteScalar()
End Sub
View 4 Replies
May 20, 2010
The scenario is that I wanna insert a record to the database via INSERT query and I need to user the identity number of this record in the INSERT query.
But I don't know how to achieve this.
Here is my table structure and code for your better understanding.
There are three columns in the Table: categoryID, categoryName, categoryPath. I need the path based on the categoryID which is an identity int column.
Now I used this code to do INSERT:
[Code]....
View 6 Replies
Mar 8, 2011
I have an insert table with identity specification set. And I getthis error. I'm using a stored procedure to store it. How do I correct it. I'm also using a details view on my insert page.
Exception Details: System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'Insert' when IDENTITY_INSERT is set to OFF.
View 4 Replies
Jun 5, 2013
I want to know if it's possible to return the identity value after an insert working with just the insertCommand and the insert parameters - something like this (but this isn't working):
Code:
<asp:SqlDataSource ID="sqlCustomerInformation" runat="server" ConnectionString="<%$ ConnectionStrings:SloanLEDLightingSystemsQuoteToolConnectionString %>"
SelectCommand="SELECT quoteCustomerInformationId,contactname FROM QuoteCustomerInformation order by quoteCustomerInformationId"
[Code] ....
Not sure what's wrong with my code. Should I be doing this in the code behind? I'm also confused as to how I would then retrieve the identity value in the code behind - on iteminserted.
View 2 Replies
Oct 9, 2010
How to copy the displayed data from grid view with LINQ?
Example:
In the GridView I have a data:
ID, Surname
1, Surname1
2, Surname2
3, Surname3
How to copy this information in the same GridView and to add new IDs.
Finally, the copy must look like this:
ID, Surname
4, Surname1
5, Surname2
6, Surname3
View 2 Replies
Apr 3, 2010
I am in a serious trouble right now, i wanted to know that how to write a query in LINQ to SQL to retrieve identity column's current value before inserting any value.
I need this cos i m building a windows app n i need to display this value before inserting a record. I have tried DataContext.ExecuteCommand('DBCC CHECKIDENT (Tablename)') but it returns the number of rows modified.
View 2 Replies
Jul 10, 2010
The wierd thing is this was working fine and then it just started throwing this error,
"Cannot insert explicit value for identity column in table 'Reports' when IDENTITY_INSERT is set to OFF."
Here is the code:
[Code]....
View 6 Replies
Dec 21, 2010
i have created a web form, where i have 3 textboxes into a table and one submit button.
i would like to store values from the textboxes into my database (sql server) when i click the submit button.
but how to insert the value that is not in textbox into database which is primary key for table without identity column.
View 11 Replies
Dec 6, 2010
This would seem to be quite a trivial task, however I am having trouble retrieving the identity of the record inserted using the detailsview.insert() in the code behind. It would seem that detailsview.DataKey.Value would contain this value, but it is null after the insert is performed.
View 4 Replies
May 18, 2010
How do I set my insert identity return value parameter in codebehind? I have working code now but i have all of my parameters set in codebehindexcept the following:
[Code]....
View 6 Replies
May 8, 2010
I have a Access DB. I have relations with two tables. For example In my table1 I have three columns as T1ID, Name, Description and Tbale2 I have three column as T2ID, T1ID which is a foreignkey from Table1 and desc.
What I want is that : for example, I wanna copy the columns from table2 which has the value of 2 under the foreignkey field and I wanna insert them into table2 again with the value of 3 under the foreignkey field !
View 4 Replies
Mar 3, 2011
I have error:
Cannot insert explicit value for identity column in table 'UserDetails' when IDENTITY_INSERT is set to OFF.
I'm trying to insert a record through a BLL (Business Logic Layer) class with an 'Insert' button attached to the FooterTemplate of a GridView2. My code:
[Code]....
[Code]....
BLL layer code:
[Code]....
The field 'idUser' is autoincremented. When I use SqlDataSource with a DetailsView, add option it adds a record and autoincrements the 'isUser'.
View 7 Replies
Jan 27, 2010
Is there a way to copy a row from one table and insert to another but at the same time insert extra values to destination table?Let's say source table Item has values:
ItemID
ItemType
ItemProducer
ItemModel
Destination table ItemHist:
ItemID
ChangeDate
ChangeReason
ChangedBy
ItemType
ItemProducer
ItemModel
I want to copy row from source table where itemid is 25, insert it into destination table and add extra values: ChangeDate, ChangeReason, ChangedBy. I tried:
INSERT INTO ItemHist (ItemID, ChangeDate, ChangeReason, ChangedBy, ItemType, ItemModel) VALUES (ItemHist.ChangeDate=GetDate(), ItemHist.ChangeReason="why not", ItemHist.ChangedBy="me")
SELECT ItemID, ItemType, ItemProducer, ItemModel FROM Item WHERE ItemId=25
but obviously it didn't work ("The name 'ChangeDate' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.").
View 4 Replies
Jan 1, 2011
I am developing a asp.net application and i am using SQL Server 2008. I took a IDENTITY column as Record_ID for detail table where i will have trillions of records per year. So just want to ask whats the largest number record id (identity) column can hold and in ASP.NET which data type i should use to handle record id as i am using this id as a reference to update the table data. I don't want to end up being trapped some day.
View 1 Replies
Mar 4, 2010
I am trying to use a DetailsView to enter a new row into my database, but need to enter a further row in a linked table at the same time.
I am able to use the "iteminserted" event to gain control after the event has completed, but I need the key to the row i just inserted into the main table.
I am using a dataset, so the insert is managed by a tableadapter which has been configured to return an integer with the newly created identity of the row i just inserted.
Does anyone know how I can get access to that identity? is it in the "e" object of iteminserted? how do i find that if it is?
Here is the VB CodeBehind I am using to insert the row in the linked table (the DetailsView has just inserted a row into the "Books" table and the database has just assigned it an identity which should have been returned to somewhere by the tableadapter. I need that identity as a key to the "BookAuthors" table):
[Code]....
This is the ASP code for the DetailsView and the DataSource:
[Code]....
And here is the code for the tableadapter i am using
[Code]....
View 5 Replies
Aug 11, 2010
I am working on a web app for an online photo album. It is the last project in Scott Mitchell's book: "ASP.Net 2.0 in 24 hours".
I am creating a page where users can enter new photo images. The functionality for uploading an image will come later. I am working on just inserting a new row into the Pictures table with an optional category, a required title and a required description.
I am getting an error when I try to insert a new row.
Here is a screenshot of the page with a shot of the dropdown list.
The Categories are user-specific. I am getting the correct values retrieved.
[URL]
There are two pretty simple database tables involved here.
NOTE: The CategoryID and PIctureID are both autoincrement integer columns.
[URL]
The page uses a DetailsView that uses a SqlDataSource that uses the Pictures table. (The DetailsView's Default Mode property is set to "Insert". The "Enable Inserting" checkbox is also checked.)
The dropdown list uses a dropdown control that uses a SqlDataSource that uses the Categories table.
When the "Insert" button is clicked the CategoryID value associated with selected (Category) Name on the dropdown list will be used along with the Title and Description values to insert a row in to the Pictures table. (If no Category value is selected, then a null value will be used for the CategoryID. This is OK because the CategoryID column in the Pictures table allows nulls.)
My problem is that I am getting this error:
Cannot insert explicit value for identity column in table 'Pictures' when IDENTITY_INSERT is set to OFF.
(FYI: I have the full version of both Visual Studio and SQL Server.)
Here is my source code for the page:
[Code]....
View 3 Replies
Feb 25, 2010
i have two sqldatasource controls. one i use to display data in textbox's ,filter'd by a select parameter in page behind code. Once checked, i want to copy this data to the other datasource ,by selecting checkbox.Then display this data in detailsview control.
At present the two datasource controls declared , render data to the page simultaneously during pageload. I want to first check data in textbox's from first source, before second datasource is rendered to screen. note, both are filtered by a page variable. i wish to leave the textbox datasource control in situ, as other controls and code depend on it.The other detailsview datasource is my problem?
View 1 Replies
Sep 20, 2010
I got the following query to group the table. I am wondering how to add a subtotal record with anonymous type.
string prevOriginator = string.Empty;
var oOriginator = (from I in dtIssue.AsEnumerable()
group I by new {RaisedBy = I.Field<string>("RaisedBy"), ItemType = I.Field<string>("ItemType")} into grp
[code]...
View 1 Replies
Oct 13, 2010
How I can write following SQL query using LINQ. There is no default constraint define for the ID column so we have explicitly pass the NEWID().
I want to replicate the products of a company to another company.
Insert Into Products Select NEWID() AS ProductID, ProductName, CompanyID = @DestinationID, ProductCategoryID From Products Where CompanyID = @SourceID
Also once I get these result how can I use InsertAllOnSubmit to insert all the records at once without looping it.
View 2 Replies
Mar 27, 2011
i have a Tag Table TagId TagName
Post Table PostId PostName
TagPost Table TagId PostId
How can i do a many to many insert into database in one transaction?
View 4 Replies
Jan 19, 2011
deleted old code
View 3 Replies