.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

How do I retrieve a new row ID immediately upon insert with LINQ?

Posted By:      Posted Date: September 26, 2010    Points: 0   Category :ASP.Net

Hi everyone-

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)


View Complete Post

More Related Resource Links

How to retrieve image from DB with Linq and diplay in Image Control


Hi all-


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"

'update DB with new Image 
        If FileUpload1.HasFile AndAlso FileUpload1.PostedFile.ContentLength > 0 Then
            'Read the file in to a byte Array.
            Dim filebyte As Byte() = FileUpload1.FileBytes
            Dim fileBinary As New System.Data.Linq.Binary(filebyte)
                Dim c3 = (From c In dc.ProductImages _
                          Where c.userID = userGuid _
                          Select c).FirstOrDefault

                c3.productImage = fileBinary

            Catch ex As Exception
                Throw ex
            End Try
Here's my attempt at the retrieval, which isn't working:
                    Dim currentImage = F

Insert a "Select User" row in Linq for a dropdown list

I'm new to Linq. I have searched and searched the web for a soluion, and can't find anything. I have a Linq query and I want to insert a row ("Select User") to the top before I pass it to the drop down list. I've been trying to use the Union but to now avail (it keeps telling me that my object doesn't support the Union method). My code, prior to attempting to inser a row, is very simple.public SelectList DropDown_Users()        {            var context = new VivarianDataContext();            var query = from t in context.AspnetUsers                        select new { t.UserId, t.LastName };            list = new SelectList(query.AsEnumerable(), "UserId", "LastName");            return list;        }Now I try to insert a row and I found this on the internet and it seems to say that his solution will work. But it is filled with syntax errors. http://magicode.wordpress.com/2009/08/20/inserting-an-item-in-iqueryable-object-using-union-met

Linq to xml to retrieve element value by its attribute

Can someone please tell me how to select the mac element value.  Here is my code that not working.  Thanks. Attempt1:        '* from string        Dim xdoc As XDocument = XDocument.Parse(xmlString)        Dim LQElements = From xe In xdoc.Elements("mac") _                         Where xe.Attribute("type").Value = "eth" _                            Select xe.Value        For Each LQElement In LQElements            Dim mytype As String = LQElement.ToString        Next Attempt2: '* from string Dim xdoc As XDocument = XDocument.Parse(xmlString) Dim LQElements = (From xe In xdoc.XPathSelectElements("//mac") _ Where xe.Attribute("type") = "eth" _ Select New With { _ .type = xe.Attribute("type").Value, _

MS Linq To SQL Samples - Insert/Update/Delete

Hi, I'm stumbling along trying my hand at Linq to SQL and have come across this code below that was provided by MS.http://msdn.microsoft.com/en-us/vbasic/bb737928.aspxThe problem is there is no ".add" method for Categories to chose in the statement db2.Categories.add(newCategory)I've seen similar videos here on ASP .NET that uses code very much like the example below, but I am unable to run this example connected to a Northwind SQL database using Web Developer 2010 Express. This is the One-to-Many example listed under Linq To SQL Samples - Insert/Update/Delete. Thanks for any help! Shawn Dim db2 = New DataClassesDataContext Dim ds = New DataLoadOptions() ds.LoadWith(Of Category)(Function(p) p.Products) db2.LoadOptions = ds Dim newCategory = New Category With {.CategoryName = "Widgets", _ .Description = "Widgets are the customer-facing analogues " & _ "to sprockets and cogs.", _ .Picture = Nothing} Dim newProduct = New Product With {.ProductName = "Blue Widget", _ .UnitPrice = 34.56#, _ .Category = newCategory, _

Linq to SQL insert to datatable


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
                            orderby grp.Key
                            select new {RecType = "D",  RaisedBy = grp.Key.RaisedBy, ItemType = grp.Key.ItemType, Count = grp.Count() });
foreach (var record in oOriginator)
    if (record.RaisedBy != prevOriginator)
        if (prevOriginator != string.Empty)
             //add a subtotal record

Using SCOPE_IDENTITY() to retrieve the id of last SQL Insert



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))
                SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
                myCommand.Parameters.AddWithValue("@userid", currentUserId);
                myCommand.Parameters.AddWithValue("@groupname", groupTextBox1.Text);
                SqlParameter groupidParameter = ne

Proper way to encode HTML for Linq insert into DB



I've installed a Free TextBox editor to allow clients to do a write up about themselves and style it with HTML.  Been reading about cross site script attacks (XSS) and want to make sure I'm correctly uploading the data collected with the Server.encode method.

Is this the right way to do it?:

Dim txt As String = TextBox1.Text
            Dim writer As New System.IO.StringWriter
            Server.HtmlEncode(txt, writer)
            Dim DC as new DataClassesDataContext

                Dim c As New Client With {.userID = userGuid, _
                                          .aboutClient = writer.ToString}


How to write SQL Insert into query using LINQ


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.

Simple LINQ to SQL Insert


I have this:

protected void btnInsert_Click(object sender, EventArgs e)
        lusHmoobDataContext lusHmoobDC = new lusHmoobDataContext();

        lusHmoob lhbLusHmoob = new lusHmoob();

        lhbLusHmoob.wordID = Guid.NewGuid();
        lhbLusHmoob.word = txtWord.Text;
        lhbLusHmoob.usage = txtUsage.Text;
        lhbLusHmoob.hmgTrans = txtEnglishTrans.Text;
        lhbLusHmoob.engTrans = txtEnglishTrans.Text;
        lhbLusHmoob.originate = txtOriginate.Text;
        lhbLusHmoob.modDate = DateTime.Now.ToLongDateString();
        lhbLusHmoob.insertDate = DateTime.Now.ToLongDateString();


And I kept getting this error even though when I compiled, there is no error.

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1061: 'lusHmoob' does not contain a definition for 'wordID' and no extension method 'wordID' acc

How to retrieve ID after Insert command when using DataSet (xsd) ?



I have created a Dataset object (XSD file)  whithin it there is a procedure called InsertWebsite.

In my code, I call this like this:

return Convert.ToInt32(Adapter.InsertWebsite(txtWebsite, txtWebsiteURL, txtWebsiteDescription, txtWebsiteURL2, txtWebsiteURL2Text, txtWebsiteURL3, txtWebsiteURL3Text, DateTime.Now, intLinkTypeID, bitIsLive, txtRecipURL, bitHasPaid, txtSubmitterName, txtSubmitterEmail, txtSubmitterIP, intCategoryID, guidUserID));

The query in the XSD dataset file is:

INSERT INTO [dbo].[tblWebsites] ([txtWebsite], [txtWebsiteURL], [txtWebsiteDescription], [txtWebsiteURL2], [txtWebsiteURL2Text], [txtWebsiteURL3], [txtWebsiteURL3Text], [dteSubmitted], [intLinkTypeID], [bitIsLive], [txtRecipURL], [bitHasPaid], [txtSubmitterName], [txtSubmitterEmail], [txtSubmitterIP], [intCategoryID],[guidUserID]) VALUES (@txtWebsite, @txtWebsiteURL, @txtWebsiteDescription, @txtWebsiteURL2, @txtWebsiteURL2Text, @txtWebsiteURL3, @txtWebsiteURL3Text, @dteSubmitted, @intLinkTypeID, @bitIsLive, @txtRecipURL, @bitHasPaid, @txtSubmitterName, @txtSubmitterEmail, @txtSubmitterIP, @intCategoryID,@guidUserID);SELECT SCOPE_IDENTITY()


When I execute the commans it retrievs value "1" which is not the actual ID genereted by Insert event.....


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

Playing with Linq grouping: GroupByMany?

One of its features is grouping. Many people understand grouping like it is defined in Sql. Linq is implementing grouping quite the same way. Let's discover this syntax and how to make consecutive groups easier.

LINQ : Implementing IN and NOT IN

I got tried of typing

var result = from s in source
where items.Contains(s)
select s;and so I implemented the IN and NOT IN methods as extension methods:

101 LINQ Samples Tutorials

101 LINQ Example with sample code snippets....This sample prints each element of an input integer array whose value is less than 5. The sample uses a query expression to create a new sequence of integers and then iterates over each element in the sequence, printing its value

Linq: how to share parameters between lambda expressions ?

When using Linq to objects, you will quickly feel the need to pass some parameters from a method to another but it's not so easy because each Linq method is not calling the following one. In a Linq sequence, each method is using the result computed by the previous one. So, local contexts are not visible from one method to another.
The compiler is using two technical different ways to let parameters go out of a method.

Linq to Sql CompiledQuery container

Ok now let's go. Here is just a little trick but with some interesting patterns that could be useful in some other contexts not connected to Linq to Sql.

When using Linq expressions, like with Linq to Sql, translating the expression into something else (sql for example) is taking time and resources. Sometimes it's negligible, sometimes not...

LINQ to SQL Paging using GridView in C# and ASP.NET 3.5

This tutorial will show you how we can extend the LINQ to SQL Class and create methods that will allow us to page data from a SQL database. C# version.
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