.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

Linq to SQL insert to datatable

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

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

View Complete Post

More Related Resource Links

Linq query to DataTable


Is there option to convert from Linq.IQueryable to DataTable with some sort of CopyToDataTable() function. I am trying this.
     var row = from p in dc.ProductModels
                  select p;
    DataTable dt = row.CopyToDataTable();

Is there option to convert from Linq.IQueryable to DataTable with some sort of CopyToDataTable() function. I am trying this.

     var row = from p in dc.ProductModels


How to handle null while converting from my datatable to List<> using LINQ


I am converting my datatable to LISt using LINQ
how do I handle nulls coming from database

List<Port> portDetails = new List<Port>();
DataTable dt = ds.Tables[0];               
portDetails = (from q in dt.AsEnumerable()
select new Port
PortCode = q.Field<string>("Code"),
ExtCode = q.Field<string>("Nb"),
Name = q.Field<string>("Name"))

In the above query if Code is null I do not want property
portcode to be set to the value it should only set if it is
not null or not blank 
PortCode = q.Field<string>("Code"),

What should be syntax
I was trying somethign like this which doesnt work
Portcode = q.Field<bool>("Code") == null ? null : q.Field<bool>("Code")


delete a row in datatable using linq to dataset

hihow can i delete a row in datatable using linq to dataset?I have a dataset in my project, need to delete some rows filtered by IDhow can i do?

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

Simple question.... LINQ on Datatable

Hi all,Simple one this I am sure for those who use LINQ! :)I basically have two tables that will be stored in viewstate until I save the data to the database.  I need a way to query the datatables, delete remove etc.  Is this possible in LINQ?So for example, delete/select rows from the DataTable that have a particular ID etc...Thanks,Mark

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, _

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


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)


How to compare two different structure datatable by using LINQ



   i have following senario in my application

DataTable1 have following structure

Dependencies                                      Tolerance

Workflow1 Lorem1 lpsum           150     

Workflow2 Lorem1 lpsum            25


DataTable 2


DataTable Comparition by usin LINQ



    i have following senario in my application

DataTable1 have following structure


Dependencies                              Tolerance

Workflow1 Lorem1 lpsum                      150  
Workflow2 Lorem1 lpsum                       25
DataTable 2

Dep_Type         Check      Dependencies

"Star Workflow" "false" "Workflow1 Lorem1 lpsum"
"Star Workflow" "false" "Workflow2 Lorem1 lpsum"
Star Workflow" "false" "Workflow4 Lorem lpsum"
Star Workflow" "false" "Workflow5 Lorem lpsum"


I want to compare two datatable, here i want to display different records from DataTable 2. how i can achieve it.


My Output should come like that, how i can achieve it through LINQ

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.

Manipulate DataTable with LinQ


I Have to manipulate filtered rows of DataTable.

Should I use the extension function dataTable.AsEnumarable() in order to filter by the extension function Where(), and the loop by foreach on the filtered IEnumerable<DataRow> collection,


should I loop by foreach and ask if() on each row?

What is better?

Insert values into a datatable.



I have a datatable with 5 columns. Then i added another column "date" to this datatable.

I want to insert value  in every row for this column in this datatable.

When i use the following i am getting  Error-- ---- Conversion from type 'DataRow' to type 'Integer' is not valid.

How can i insert values into a datatable?



 Public Sub insertBrktoDB()

    Dim mydt As New DataTable
    mydt = BreaksCSV()
    Dim dt As DataColumn = New DataColumn("Date")
    dt.DataType = System.Type.GetType("System.DateTime")
    mydt.Columns.Add(dt) '--------------p_date is a property which has the value to be inserted
    p_date = ds_rte.Tables("sched").Rows(1).Item("mdate").ToString

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

Moving data from datatable to XML using Linq


I have a data table I need to convert to XML. I know I can use datable.WriteXML but I need to rename the elements as the column names coming from the Oracle db are ugly. I found this snippet somewhere:

XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
                        new XElement("products", from p in dt
                         select new XElement("product",
                             new XAttribute("guid", p.ProductId),
                             new XAttribute("title", p.Title),
                             new XAttribute("version", p.Version))));


It looks like

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.
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