ADO.NET :: Retrieve A New Row ID Immediately Upon Insert With LINQ?
Sep 26, 2010
How can I retrieve the row ID immediately as I insert a new record with LINQ? I need to refer back to it to update the row since it will be the only unique data in this particular table ( it's the primary key and the ID number is auto generated)
As you see the record_dates property is defined as a component field of type DateMetaDate. Both created_at and updated_at fields in 'tags' table are updated via triggers. Thus I can insert a new record like such:
var newTag = new Tag() { name = "some string here" } Int32 id = (Int32)Session.Save(tag); Session.Flush(); ITag t = Session.Get<Tag>(id); ViewData["xxx"] = t.name; // -----> not null ViewData["xxx"] = t.record_dates.created_at; // -----> is null
However when querying the same record back immediately after it was inserted the record_dates field ends up null even though in the table those fields have got values.
why the Session.Get ignores getting everything back from the table? is it because it caches the newly created record for which the records_dates is null? If so how can it be told to ignore the cached version?
I wish to retrieve data from a DataTable using Linq, and I do this by first creating a DataTable with the data and then using Linq to query:
[Code]....
My problem is, that the column "enddatee" has 'holes', meaning that some rows does not have a value. This means that the convertion to DateTime will fail for some rows. How can I get around that?
I want to get the customers info and companies of this companies of products they deal with here is my query in linq
var query = from sd in db.Survey_Details select new {[code]...
customer table has about 3000 customer who every one of them fill a survey of 2500 product till now survey_details table has about 90,000 recored an will increase by 100% every year this query run good without binding in RowDataBound when i want to work with RowDataBound this is too slow and data never come i think i may take about 5 hours to come
i have a link query that retrun all the records that have their status = 'completed' ordered by their ids, but i want to return only three records not all the records
I need to get the id of a record created so that I can store that ifnormation in another SQL table. A snipet of my c#code is as follows:
string insertSql = "INSERT INTO [Group] ([userid], [groupname]) VALUES (@userid, @groupname); SET @groupid = SCOPE_IDENTITY()"; using (SqlConnection myConnection = new SqlConnection(connectionString)) { myConnection.Open(); SqlCommand myCommand = new SqlCommand(insertSql, myConnection); myCommand.Parameters.AddWithValue("@userid", currentUserId); myCommand.Parameters.AddWithValue("@groupname", groupTextBox1.Text); SqlParameter groupidParameter = new SqlParameter("@groupid", SqlDbType.Int); groupidParameter.Direction = ParameterDirection.Output; myCommand.Parameters.Add(groupidParameter); myCommand.ExecuteNonQuery(); myCommand.ExecuteNonQuery(); gid = (int)groupidParameter.Value; myConnection.Close(); }
The problem is that I am not getting the @groupid from the SET @groupid = SCOPE_IDENTITY() that is appended to the INSERT statement. The groupid in the SQL table is the Key of type uniqueidentifier
I'm using the file upload to let the user upload a single file. Here's the code I'm using to then upload to the DB. How do I reverse this process and dowload the image into the control for it to display on a different page? Here's my code for the upload - which I think works but can't confirm until I can see the download since all I see in the DB is "binary data"
I need to know how to extract the result of the attempted LINQ query below and set it equal to the strFile variable.Everything Intellisensed OK here but ine 5 shows a syntax error at the parenthesis.
i want to insert a word document in to database and retrive it ...while retriving it would be better to view in a webpage the doc file. Else after retriving there should be download buttons for each document ...clicking leads to the ordinary document download
I have a Timestamp column in my Table. I want to read the date time value and display in UI.
In Linq the Timestamp column is represented as System.Data.Linq.Binary.
I dont know how to retirve date time value in "MM-dd-YYYY" format from this Linq.Binary
- Why I am using Timestamp?.
I want to perform some operations based on the last modified date time of the particular row. Since I am using TimeStamp column in my Table as version column, It will contain the last modified date details, So i want to read the date time value from this time stamp column to do some other operations.
is there any way I can retrieve the identity value (auto generated primary key value), of a column after inserting a new database record using linq to sql? i could i achieve this like this using stored procedure: //***insert some recor*** return @@identity. how do I achieve thesame with linq to sql
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
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.
Iam inserting ,updating in one DBfunction .i want to retrieve identityvalue when in insert.for that am adding select SCOPE_IDENTITY() in insert statement.how i can i get this value??
public int funAddEdit_rtblIncidentTypesDB(clsCM_Inc_IncidentTypesData objData, int actiontype) { string qry = ""; if (actiontype == 1) qry = "INSERT INTO _rtblIncidentType (cDescription,iEscGroupID,bAllowOverride,bRequireContract,iIncidentTypeGroupID,iWorkflowID,bAllowOverrideIncidentType,bPOIncidentType,cDefaultOutline) VALUES ('" + objData.cDescription + "'," + objData.iEscGroupID + ",'" + objData.bAllowOverride + "','" + objData.bRequireContract + "'," + objData.iIncidentTypeGroupID + "," + objData.iWorkflowID + ",'" + objData.bAllowOverrideIncidentType + "','" + objData.bPOIncidentType + "','" + objData.cDefaultOutline + "'); select SCOPE_IDENTITY() "; else if (actiontype == 2) qry = "UPDATE _rtblIncidentType SET cDescription='" + objData.cDescription + "' WHERE idIncidentType=" + objData.idIncidentType; int result = SqlHelper.ExecuteNonQuery(clsHelper.ConnectionString.ToString(), CommandType.Text, qry); return result; }
if i exceute the above query individually,it returns iddentity value,,bt unable to retireve the value in codebehind.
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
in database I have House_info table that has description column and if I enter text in textbox1 it update description column now problem is when I enter text in textbox1 it didn't change text and didn't update data in database...
I put breakpoint in imagebutton2_click event and see in this code
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?
I have a view on my database and I am trying to add a new record using the AddTo method but it is not working. I noticed that LinqToEntities is creating the insert statement like this
Insert into (select field1, field2 from my_view) (field1, field2) values (value1, value2)
Is it possible to make LinqToEntities create the insert statement like the one below ?
Insert into my_view (field1, field2) values (value1, value2)