Skip to content

LINQ

LINQ (all flavours)

This category can be followed from the open social web via the handle linq-e04cf296@forum.codeproject.com

783 Topics 2.8k Posts
  • Convert Inner Join to LInq???

    question database csharp linq help
    3
    0 Votes
    3 Posts
    0 Views
    E
    I didn't test it so check it and please tell me if it's working as expected. from promo_code in tbl_promo_codes // think of it like "foreach (var promo_code in tbl_promo_codes)" where promo_code.IDPromoCode = 1 // i think it's better to write it here than any of the places labeled "//where" so you filter before any joins but i might be wrong join xref_product_promo_code in tbl_xref_product_promo_code on promo_code.IDPromoCode equals xref_product_promo_code.IDPromoCode // specifying that you're doing join with another table. join must be followed by "on .. equals" //where join product in tbl_products on xref_product_promo_code.IDPrice equals product.ProductID //where select new { product.ProductName, xref_product_promo_code.Price }; // returning an IEnumerable of a "new anonymous type" that contains two properties, ProductName and Price Eslam Afifi
  • Missing templates in Visual studio 2008

    csharp help visual-studio wpf wcf
    2
    0 Votes
    2 Posts
    0 Views
    A
    (I might sound stupid) It should be .Net 3.5 by default(that's what showing on mine) but did you check the framework version displayed on the new website dialog box ?(on the top right corner of the dialog)
  • How do I identify that a record is a result or a Default?

    question
    2
    0 Votes
    2 Posts
    0 Views
    M
    Check if myObject == default(SomeObject). Obviously, if the there is a single result whose value is the default falue (e.g. 0 if SomeObject is an int), you can't tell apart form the case when there is no value and the default is returned. You can always check context.Table.Count() != 0 to see if there are values, or use context.Table.Single() and handle the exception if there are no values.
  • Using linq to get data from a datatable

    csharp database linq tutorial
    7
    0 Votes
    7 Posts
    0 Views
    M
    With thanks to ABitSmart a solution was found. string sDescription = "Source system"; int iTypeID = (from t in oTable.AsEnumerable() where t.Field("Description").ToLower() == sDescription.ToLower() select t.Field("TypeID")).FirstOrDefault(); iTypeID has a value of 0 ot the matching ID Never underestimate the power of human stupidity RAH
  • Get Hierarchical Data Using Linq2Sql

    database help question data-structures
    1
    0 Votes
    1 Posts
    0 Views
    No one has replied
  • Problems with Except method

    csharp xml help question
    3
    0 Votes
    3 Posts
    0 Views
    G
    Thanks for your reply Gideon. I *think* the problem was that I was comparing items of IEnumerable(Of System.IO.FileInfo) and IEnumerable(Of <anonymous type>, System.IO.Fileinfo), as produced by the queries for mediaFiles and mediaOnFileSystemAndInXML respectively. Anyway, I have since found what I think is a more elegant solution (at least in terms of length of code): Public Sub UpdateXML() Try Dim doc = XDocument.Load(My.Settings.xmlMedia) Dim newTvShows As New Collections.Generic.List(Of XElement) Dim showPathInXML = From s In doc...<tvshow> \_ Select s.<path>.Value For Each filePath As String In My.Computer.FileSystem.GetFiles(My.Settings.mediaFolder) Dim fileInfo As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath) If CheckValidExtention(fileInfo.Extension) = False Then Continue For If showPathInXML.Any(Function(f) f = fileInfo.FullName) = False Then newTvShows.Add(<tvshow> <path><%= fileInfo.FullName %></path> <dateAdded><%= fileInfo.CreationTime %></dateAdded> <seen><%= "0" %></seen> <name><%= fileInfo.Name %></name> <deleted><%= "0" %></deleted> </tvshow> ) End If Next For Each ntvs As XElement In newTvShows doc.<torrss>.<tvshows>(0).Add(ntvs) Next doc.Save(My.Settings.xmlMedia) Catch ex As Exception ErrorNotifyer("Error updating XML.") End Try End Sub I think the lesson here for me was that LINQ is a wonderful tool to be used sparingly. :)
  • Grouping with LINQ

    csharp linq question
    10
    0 Votes
    10 Posts
    0 Views
    J
    You are trying to group and join at the same time, which is actually quite problematic in LINQ. Instead, join and select the fields you need into a new result set, then group that result set. Like so: var rsDailyHoursTC = from rs in ( from d in Empctx.DailyHoursTimeCategories join tc in Empctx.TimeCategories on d.TimeCategoryID equals tc.TimeCategoryID where empCatList.Contains(d.DailyHoursID) select new { TimeCategoryName = tc.TimeCategoryName, Hours = d.Hours, Minutes = d.Min } ) group rs by rs.TimeCategoryName into g select new { Category = g.Key, Hours = g.Sum(r => r.Hours), Minutes = g.Sum(r => r.Minutes) };
  • Grouping question

    csharp question database linq
    5
    0 Votes
    5 Posts
    0 Views
    J
    Your group is grouping by a LOT of fields, so I am guessing that the broad set of data for grouping is making each row unique. In LINQ to SQL, like SQL itself, when you group, to access non-grouped data you need to aggregate it. Also like SQL, if you group on a primary key (which I assume SourceID is), then each row is guaranteed to be unique, and there isn't any point in grouping. Assuming you have a simple set like this: TABLE PersonAges ID, FirstName, LastName, Age ---------------------------- 1, Jon, Doe, 24 2, Jane, Doe, 22 3, Roger, Doe, 48 4, Judy, Doe, 51 5, Jack, Smith, 47 6, Audrey, Smith, 44 And you want to find the average age of members of each last name: var agesByLastName = from pa in db.PersonAges group pa by pa.LastName into g select new { LastName = g.Key, AverageAge = g.Average(pa => pa.Age) };
  • Linq to xml

    database help csharp linq xml
    2
    0 Votes
    2 Posts
    0 Views
    G
    Assuming you have the data in a variable named xmlData, you should need something like this: Dim value = From elem In xmlData.<johnr> _ Where elem.<setting>.Value = "frmMainForm" AndAlso _ elem.<key>.Value = "LastLocale" _ Select elem.<value>.Value
  • Help for writing a LINQ query !

    csharp database linq xml help
    9
    0 Votes
    9 Posts
    0 Views
    F
    Not a problem, glad to help.
  • Problem with Store Procedure

    csharp sharepoint database wcf help
    2
    0 Votes
    2 Posts
    0 Views
    H
    The designer does try to analyse a SPROC to determine the output type but it's very limited, and in this case you're returning from a temp table based on constructed SQL - it would be difficult to determine what this is. Your best bet is to create a class manually that can hold the results and specify in the designer that it returns that type. Try reading "Handling Multiple Result Shapes from SPROCs" in http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx[^] 'Howard
  • Multi threaded data access issues

    database csharp linq com testing
    5
    0 Votes
    5 Posts
    1 Views
    H
    Howard Richards wrote: Your code looks like the calc is creating its own datacontext within each thread instance This assumption is correct... The CalcData method (The method that executes in the seperate thread)inside of EmployeeCalculationClass is a "calculation overview" if you will. Its content is as follows // // Check data and throw exceptions where necicary CheckData(); // // Prepare The Process Period List PopulateProcessPeriodList(); // // Prepare the Organized Punches List PrepareOrganizedPunches(); // // Loop each Process Period And do the calculation for // That specific day. foreach (ProcessPeriod pp in ProcessPeriodList) { ProcessDailyData(pp); } Each one of those methods start of with a using (EmployeeDataContext ctx = new EmployeeDataContext(sqlConnectionString)) code block. ProcessDailyData(); is an "overview method" for daily calculations so it also has helper methods that all have their own using (EmployeeDataContext ctx = new EmployeeDataContext(sqlConnectionString)) code block. So do you have any idea why I'm getting the exceptions when I'm running 20 threads at a time but not when I'm only running one thread at a time? Thanks Howard Harvey Saayman - South Africa Software Developer .Net, C#, SQL you.suck = (you.Passion != Programming & you.Occupation == jobTitles.Programmer) 1000100 1101111 1100101 1110011 100000 1110100 1101000 1101001 1110011 100000 1101101 1100101 1100001 1101110 100000 1101001 1101101 100000 1100001 100000 1100111 1100101 1100101 1101011 111111 modified on Wednesday, February 11, 2009 7:55 AM
  • LINQ concepts with Treenode array

    csharp linq data-structures tutorial
    2
    0 Votes
    2 Posts
    0 Views
    H
    try ad.Nodes.Contains(selNode) ? 'Howard
  • Linq Merge

    csharp linq question
    2
    0 Votes
    2 Posts
    0 Views
    H
    No. 'Howard
  • 0 Votes
    2 Posts
    0 Views
    H
    I think the main problem here is multiple app domains in ASP.NET. Setting u.Views += 1 is nice but with ASP.NET you could have several instances of the application - they would both update Views independently so the value is wrong. The way to solve that would be to store the number of views as a field on the user in the database. Then the issue becomes how do you update it? There isn't in LINQ to SQL a hook for selection e.g. OnUserSelect() as there is for updates/inserts etc. Instead I would suggest a static method on the User class for doing the selection that updates the count and returns the user in one go. The first thing this method does is call a stored procedure, lets say UpdateUserCount(username) which updates the count value of the user you're about to access. Then the routine does the LINQ select and returns the user. for example: public static User SelectUser(string username) { var dx = new MyDataContext(); dx.UpdateUserCount(username); return dx.Users.Single( u => u.Username == username); } 'Howard
  • 0 Votes
    2 Posts
    0 Views
    H
    Wierd.. I was trying to check this using a test project using Northwind and a simple LINQ to SQL Datacontext. I find that the code generated for this datacontext has a check to see if the related object is loaded for an association, e.g. : <Column(Storage:="_CustomerID", DbType:="NChar(5)")> _ Public Property CustomerID() As String Get Return Me._CustomerID End Get Set If (String.Equals(Me._CustomerID, value) = false) Then If Me._Customer.HasLoadedOrAssignedValue Then _ Throw New System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException End If Me.OnCustomerIDChanging(value) Me.SendPropertyChanging Me._CustomerID = value Me.SendPropertyChanged("CustomerID") Me.OnCustomerIDChanged End If End Set End Property Yet my datacontext does not have this code for the foreign keys.. and I cannot see any reason why it should be different. Any ideas anyone?? 'Howard
  • 0 Votes
    4 Posts
    0 Views
    F
    I found another solution and I think it is easier and maybe better for my needs Expression Filter; // this the expression that may have many internal Conditions Expression Result = Expression.Call(Expression.Property(Filter,"FirstName") ,typeof(string).GetMethod("Contains") ,new Expression[] {Expression.Constant("fe" ,typeof(string))} ); I found this code in LinqInAction Book Page 498 Thanks Again mr Eslam Afifi I hope to be friends :) You have To Search About The Truth Of Your Life Why Are you Here In Life ?
  • Creating sql database by using Link???? [modified]

    database question csharp linq
    5
    0 Votes
    5 Posts
    0 Views
    R
    Follow this link http://www.asp.net/learn/linq-videos/[^] i think u can solve ur prob.. than:thumbsup:x
  • Multi Level Descendants

    xml question
    2
    0 Votes
    2 Posts
    0 Views
    A
    I think I have found the answer (so soon :-D ), this worked for me, is it the correct way? var fields = (from bif in bodyItemNode.Elements("Fields").Descendants("Field") ____________________________________________________________ Be brave little warrior, be VERY brave
  • What are the differences ?

    question
    5
    0 Votes
    5 Posts
    0 Views
    F
    Not a problem, glad I was able to help :)