Search Results

Search found 6744 results on 270 pages for 'linq to entities'.

Page 4/270 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • LINQ 2 Entities , howto check DateTime.HasValue within the linq query

    - by Snoop Dogg
    Hi all ... I have this method that is supposed to get the latest messages posted, from the Table (& EntitySet) called ENTRY ///method gets "days" as parameter, used in new TimeSpan(days,0,0,0);!! using (Entities db = new Entities()) { var entries = from ent in db.ENTRY where ent.DATECREATE.Value > DateTime.Today.Subtract(new TimeSpan(days, 0, 0, 0)) select new ForumEntryGridView() { id = ent.id, baslik = ent.header, tarih = ent.entrydate.Value, membername = ent.Member.ToString() }; return entries.ToList<ForumEntryGridView>(); } Here the DATECREATED is Nullable in the database. I cant place "if"s in this query ... any way to check for that? Thx in advance

    Read the article

  • Entity LINQ on many-to-many got error "LINQ to Entities does not recognize the method 'Boolean Conta

    - by user300992
    I have 2 tables (Users and Roles) they are mapped as Many-to-Many in relational db. When I imported to Entity Data Content, they are still staying as the same relationship. Since they are mapped as Many-To-Many in Entity, I can access Users.RoleCollection or Roles.UserCollection However, when I execute this LINQ query, I got "LINQ to Entities does not recognize the method 'Boolean Contains... method, and this method cannot be translated into a store expression." var result (from a in Users from b in Roles where a.RoleCollection.Contains(b) select a); I think I must did something wrong... please help.

    Read the article

  • Can't enumerate LinQ results with left join

    - by nvtthang
    var itemSet = from item in da.GetList<Models.account>() join file in objFileStorageList on item.account_id equals file.parent_id into objFile from fileItem in objFile.DefaultIfEmpty() where item.company != null && item.company.company_id == 123 orderby item.updatedDate descending select new { Id = item.account_id, RefNo = item.refNo, StartDate = item.StartDate , EndDate = item.EndDate , Comment = item.comment, FileStorageID = fileItem != null ? fileItem.fileStorage_id : -1, Identification = fileItem != null ? fileItem.identifier : null, fileName = fileItem != null ? fileItem.file_nm : null }; It raises error message when I try to enumerate through collection result from Linq query above. LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable1[SCEFramework.Models.fileStorage] DefaultIfEmpty[fileStorage](System.Collections.Generic.IEnumerable1[SCEFramework.Models.fileStorage])' method, and this method cannot be translated into a store expression foreach (var item in itemSet) { string itemRef= item.RefNo; } Please suggest me any solutions. Thanks in advance.

    Read the article

  • Help with Linq and Generics

    - by Jonathan
    Hi to all. I'm triying to make a function that add a 'where' clause to a query based in a property and a value. This is a very simplefied version of my function. Private Function simplified(ByVal query As IQueryable(Of T), ByVal PValue As Long, ByVal p As PropertyInfo) As ObjectQuery(Of T) query = query.Where(Function(c) DirectCast(p.GetValue(c, Nothing), Long) = PValue) Dim t = query.ToList 'this line is only for testing, and here is the error raise Return query End Function The error message is: LINQ to Entities does not recognize the method 'System.Object CompareObjectEqual(System.Object, System.Object, Boolean)' method, and this method cannot be translated into a store expression. Looks like a can't use GetValue inside a linq query. Can I achieve this in other way? Post your answer in C#/VB. Chose the one that make you feel more confortable. Thanks

    Read the article

  • Filtering data in LINQ with the help of where clause

    - by vik20000in
     LINQ has bought with itself a super power of querying Objects, Database, XML, SharePoint and nearly any other data structure. The power of LINQ lies in the fact that it is managed code that lets you write SQL type code to fetch data.  Whenever working with data we always need a way to filter out the data based on different condition. In this post we will look at some of the different ways in which we can filter data in LINQ with the help of where clause. Simple Filter for an array. Let’s say we have an array of number and we want to filter out data based on some condition. Below is an example int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums =                 from num in numbers                 where num < 5                 select num;   Filter based on one of the property in the class. With the help of LINQ we can also filer out data from a list based on value of some property. var soldOutProducts =                 from prod in products                 where prod.UnitsInStock == 0                 select prod; Filter based on Multiple of the property in the class. var expensiveInStockProducts =         from prod in products         where prod.UnitsInStock > 0 && prod.UnitPrice > 3.00M         select prod; Filter based on the index of the Item in the list.In the below example we can see that we are able to filter data based on the index of the item in the list. string[] digits = { "zero", "one", "two", "three", "four", "five", "six"}; var shortDigits = digits.Where((digit, index) => digit.Length < index); There are many other way in which we can filter out data in LINQ. In the above post I have tried and shown few ways using the LINQ. Vikram

    Read the article

  • Union,Except and Intersect operator in Linq

    - by Jalpesh P. Vadgama
    While developing a windows service using Linq-To-SQL i was in need of something that will intersect the two list and return a list with the result. After searching on net i have found three great use full operators in Linq Union,Except and Intersect. Here are explanation of each operator. Union Operator: Union operator will combine elements of both entity and return result as third new entities. Except Operator: Except operator will remove elements of first entities which elements are there in second entities and will return as third new entities. Intersect Operator: As name suggest it will return common elements of both entities and return result as new entities. Let’s take a simple console application as  a example where i have used two string array and applied the three operator one by one and print the result using Console.Writeline. Here is the code for that. C#, using GeSHi 1.0.8.6 using System; using System.Collections.Generic; using System.Linq; using System.Text;     namespace ConsoleApplication1 {     class Program     {         static void Main(string[] args)         {             string[] a = { "a", "b", "c", "d" };             string[] b = { "d","e","f","g"};               var UnResult = a.Union(b);             Console.WriteLine("Union Result");               foreach (string s in UnResult)             {                 Console.WriteLine(s);                          }               var ExResult = a.Except(b);             Console.WriteLine("Except Result");             foreach (string s in ExResult)             {                 Console.WriteLine(s);             }               var InResult = a.Intersect(b);             Console.WriteLine("Intersect Result");             foreach (string s in InResult)             {                 Console.WriteLine(s);             }             Console.ReadLine();                        }          } }   Parsed in 0.022 seconds at 45.54 KB/s Here is the output of console application as Expected. Hope this will help you.. Technorati Tags: Linq,Except,InterSect,Union,C#

    Read the article

  • LINQ aggregate left join on SQL CE

    - by P Daddy
    What I need is such a simple, easy query, it blows me away how much work I've done just trying to do it in LINQ. In T-SQL, it would be: SELECT I.InvoiceID, I.CustomerID, I.Amount AS AmountInvoiced, I.Date AS InvoiceDate, ISNULL(SUM(P.Amount), 0) AS AmountPaid, I.Amount - ISNULL(SUM(P.Amount), 0) AS AmountDue FROM Invoices I LEFT JOIN Payments P ON I.InvoiceID = P.InvoiceID WHERE I.Date between @start and @end GROUP BY I.InvoiceID, I.CustomerID, I.Amount, I.Date ORDER BY AmountDue DESC The best equivalent LINQ expression I've come up with, took me much longer to do: var invoices = ( from I in Invoices where I.Date >= start && I.Date <= end join P in Payments on I.InvoiceID equals P.InvoiceID into payments select new{ I.InvoiceID, I.CustomerID, AmountInvoiced = I.Amount, InvoiceDate = I.Date, AmountPaid = ((decimal?)payments.Select(P=>P.Amount).Sum()).GetValueOrDefault(), AmountDue = I.Amount - ((decimal?)payments.Select(P=>P.Amount).Sum()).GetValueOrDefault() } ).OrderByDescending(row=>row.AmountDue); This gets an equivalent result set when run against SQL Server. Using a SQL CE database, however, changes things. The T-SQL stays almost the same. I only have to change ISNULL to COALESCE. Using the same LINQ expression, however, results in an error: There was an error parsing the query. [ Token line number = 4, Token line offset = 9,Token in error = SELECT ] So we look at the generated SQL code: SELECT [t3].[InvoiceID], [t3].[CustomerID], [t3].[Amount] AS [AmountInvoiced], [t3].[Date] AS [InvoiceDate], [t3].[value] AS [AmountPaid], [t3].[value2] AS [AmountDue] FROM ( SELECT [t0].[InvoiceID], [t0].[CustomerID], [t0].[Amount], [t0].[Date], COALESCE(( SELECT SUM([t1].[Amount]) FROM [Payments] AS [t1] WHERE [t0].[InvoiceID] = [t1].[InvoiceID] ),0) AS [value], [t0].[Amount] - (COALESCE(( SELECT SUM([t2].[Amount]) FROM [Payments] AS [t2] WHERE [t0].[InvoiceID] = [t2].[InvoiceID] ),0)) AS [value2] FROM [Invoices] AS [t0] ) AS [t3] WHERE ([t3].[Date] >= @p0) AND ([t3].[Date] <= @p1) ORDER BY [t3].[value2] DESC Ugh! Okay, so it's ugly and inefficient when run against SQL Server, but we're not supposed to care, since it's supposed to be quicker to write, and the performance difference shouldn't be that large. But it just doesn't work against SQL CE, which apparently doesn't support subqueries within the SELECT list. In fact, I've tried several different left join queries in LINQ, and they all seem to have the same problem. Even: from I in Invoices join P in Payments on I.InvoiceID equals P.InvoiceID into payments select new{I, payments} generates: SELECT [t0].[InvoiceID], [t0].[CustomerID], [t0].[Amount], [t0].[Date], [t1].[InvoiceID] AS [InvoiceID2], [t1].[Amount] AS [Amount2], [t1].[Date] AS [Date2], ( SELECT COUNT(*) FROM [Payments] AS [t2] WHERE [t0].[InvoiceID] = [t2].[InvoiceID] ) AS [value] FROM [Invoices] AS [t0] LEFT OUTER JOIN [Payments] AS [t1] ON [t0].[InvoiceID] = [t1].[InvoiceID] ORDER BY [t0].[InvoiceID] which also results in the error: There was an error parsing the query. [ Token line number = 2, Token line offset = 5,Token in error = SELECT ] So how can I do a simple left join on a SQL CE database using LINQ? Am I wasting my time?

    Read the article

  • whats wrong in this LINQ synatx?

    - by Saurabh Kumar
    Hi, I am trying to convert a SQL query to LINQ. Somehow my count(distinct(x)) logic does not seem to be working correctly. The original SQL is quite efficient(or so i think), but the generated SQL is not even returning the correct result. I am trying to fix this LINQ to do what the original SQL is doing, AND in an efficient way as the original query is doing. Help here would be really apreciated as I am stuck here :( SQL which is working and I need to make a comparable LINQ of: SELECT [t1].[PersonID] AS [personid] FROM [dbo].[Code] AS [t0] INNER JOIN [dbo].[phonenumbers] AS [t1] ON [t1].[PhoneCode] = [t0].[Code] INNER JOIN [dbo].[person] ON [t1].[PersonID]= [dbo].[Person].PersonID WHERE ([t0].[codetype] = 'phone') AND ( ([t0].[CodeDescription] = 'Home') AND ([t1].[PhoneNum] = '111') OR ([t0].[CodeDescription] = 'Work') AND ([t1].[PhoneNum] = '222') ) GROUP BY [t1].[PersonID] HAVING COUNT(DISTINCT([t1].[PhoneNum]))=2 The LINQ which I made is approximately as below: var ids = context.Code.Where(predicate); var rs = from r in ids group r by new { r.phonenumbers.person.PersonID} into g let matchcount=g.Select(p => p.phonenumbers.PhoneNum).Distinct().Count() where matchcount ==2 select new { personid = g.Key }; Unfortunately, the above LINQ is NOT generating the correct result, and is actually internally getting generated to the SQL shown below. By the way, this generated query is also reading ALL the rows(about 19592040) around 2 times due to the COUNTS :( Wich is a big performance issue too. Please help/point me to the right direction. Declare @p0 VarChar(10)='phone' Declare @p1 VarChar(10)='Home' Declare @p2 VarChar(10)='111' Declare @p3 VarChar(10)='Work' Declare @p4 VarChar(10)='222' Declare @p5 VarChar(10)='2' SELECT [t9].[PersonID], ( SELECT COUNT(*) FROM ( SELECT DISTINCT [t13].[PhoneNum] FROM [dbo].[Code] AS [t10] INNER JOIN [dbo].[phonenumbers] AS [t11] ON [t11].[PhoneType] = [t10].[Code] INNER JOIN [dbo].[Person] AS [t12] ON [t12].[PersonID] = [t11].[PersonID] INNER JOIN [dbo].[phonenumbers] AS [t13] ON [t13].[PhoneType] = [t10].[Code] WHERE ([t9].[PersonID] = [t12].[PersonID]) AND ([t10].[codetype] = @p0) AND ((([t10].[codetype] = @p1) AND ([t11].[PhoneNum] = @p2)) OR (([t10].[codetype] = @p3) AND ([t11].[PhoneNum] = @p4))) ) AS [t14] ) AS [cnt] FROM ( SELECT [t3].[PersonID], ( SELECT COUNT(*) FROM ( SELECT DISTINCT [t7].[PhoneNum] FROM [dbo].[Code] AS [t4] INNER JOIN [dbo].[phonenumbers] AS [t5] ON [t5].[PhoneType] = [t4].[Code] INNER JOIN [dbo].[Person] AS [t6] ON [t6].[PersonID] = [t5].[PersonID] INNER JOIN [dbo].[phonenumbers] AS [t7] ON [t7].[PhoneType] = [t4].[Code] WHERE ([t3].[PersonID] = [t6].[PersonID]) AND ([t4].[codetype] = @p0) AND ((([t4].[codetype] = @p1) AND ([t5].[PhoneNum] = @p2)) OR (([t4].[codetype] = @p3) AND ([t5].[PhoneNum] = @p4))) ) AS [t8] ) AS [value] FROM ( SELECT [t2].[PersonID] FROM [dbo].[Code] AS [t0] INNER JOIN [dbo].[phonenumbers] AS [t1] ON [t1].[PhoneType] = [t0].[Code] INNER JOIN [dbo].[Person] AS [t2] ON [t2].[PersonID] = [t1].[PersonID] WHERE ([t0].[codetype] = @p0) AND ((([t0].[codetype] = @p1) AND ([t1].[PhoneNum] = @p2)) OR (([t0].[codetype] = @p3) AND ([t1].[PhoneNum] = @p4))) GROUP BY [t2].[PersonID] ) AS [t3] ) AS [t9] WHERE [t9].[value] = @p5 Thanks!

    Read the article

  • EF/LINQ: Where() against a property of a subtype

    - by ladenedge
    I have a set of POCOs, all of which implement the following simple interface: interface IIdObject { int Id { get; set; } } A subset of these POCOs implement this additional interface: interface IDeletableObject : IIdObject { bool IsDeleted { get; set; } } I have a repository hierarchy that looks something like this: IRepository<T <: BasicRepository<T <: ValidatingRepository<T (where T is IIdObject) I'm trying to add a FilteringRepository to the hierarchy such that all of the POCOs that implement IDeletableObject have a Where(p => p.IsDeleted == false) filter applied before any other queries take place. My goal is to avoid duplicating the hierarchy solely for IDeletableObjects. My first attempt looked like this: public override IQueryable<T> Query() { return base.Query().Where(t => ((IDeletableObject)t).IsDeleted == false); } This works well with LINQ to Objects, but when I switch to an EF backend I get: "LINQ to Entities only supports casting Entity Data Model primitive types." I went on to try some fancier parameterized solutions, but they ultimately failed because I couldn't make T covariant in the following case for some reason I don't quite understand: interface IQueryFilter<out T> // error { Expression<Func<T, bool>> GetFilter(); } I'd be happy to go into more detail on my more complicated solutions if it would help, but I think I'll stop here for now in hope that someone might have an idea for me to try. Thanks very much in advance!

    Read the article

  • Load parent and child table in one query linq to entitiy

    - by parminder
    Hi Experts, I have a following tables/classes structure in Linq to entities. ` Books { bookId, Title } Tags { TagId Tag } BooksTags { BookId TagId } ' Now I need to write a query which gives me result like this Class Result { bookId, Title Tags } Tags should be comma separated text from the tags table by joining all three tables. How to get it done. Thanks Parminder

    Read the article

  • Linq with EF dynamic search

    - by malik
    I am using EF 3.5 with MVC. I want to made a search page, has some fields for criteria like date, int etc. What is the way in linq to entities to filter the result dynamically. If there are one parameter we can use .where(a=a.id==1) but many combination with optional param how can i load results and then pass to model.

    Read the article

  • LINQ to SQL - Tracking New / Dirty Objects

    - by Joseph Sturtevant
    Is there a way to determine if a LINQ object has not yet been inserted in the database (new) or has been changed since the last update (dirty)? I plan on binding my UI to LINQ objects (using WPF) and need it to behave differently depending whether or not the object is already in the database. MyDataContext context = new MyDataContext(); MyObject obj; if (new Random().NextDouble() > .5) obj = new MyObject(); else obj = context.MyObjects.First(); // How can I distinguish these two cases? The only simple solution I can think of is to set the primary key of new records to a negative value (my PKs are an identity field and will therefore be set to a positive integer on INSERT). This will only work for detecting new records. It also requires identity PKs, and requires control of the code creating the new object. Is there a better way to do this? It seems like LINQ must be internally tracking the status of these objects so that it can know what to do on context.SubmitChanges(). Is there some way to access that "object status"? Clarification Apparently my initial question was confusing. I'm not looking for a way to insert or update records. I'm looking for a way, given any LINQ object, to determine if that object has not been inserted (new) or has been changed since its last update (dirty).

    Read the article

  • Castle ActiveRecord / NHibernate Linq Querys with ValueTypes

    - by Thomas Schreiner
    Given the following code for our Active Record Entites and ValueTypes Linq is not working for us. [ActiveRecord("Person")] public class PersonEntity : ActiveRecordLinqBase<PersonEntity> { string _name; [Property("Name", Length = 20, ColumnType = "string", Access = PropertyAccess.FieldCamelcaseUnderscore)] public Name Name { get { return NameValue.Create(_name);} set { _name = value.DataBaseValue; } } ... } public abstract class Name : IValueType { string DataBaseValue {get;set;} ... } public class Namevalue : Name { string _name; private NameValue(string name) { _name = name; } public static NameValue Create(string name) { return new NameValue(name); } ... } We tried to use linq in the following way so far with no success: var result = from PersonEntity p in PersonEntity.Queryable where p.Name == "Thomas" select p; return result.First(); // throws exception Cannot convert string into Name We tried and implemented a TypeConverter for Name, but the converter never got called. Is there a way to have linq working with this ValueTypes? Update: Using NHibernate.UserTypes.IUserType it sortof works. I Implemented the Interface as described here: http://stackoverflow.com/questions/1565056/how-to-implement-correctly-iusertype I still had to add a ConversionOperator from string to Name and had to call it Explicitly in the linq Statement, even though it was defined as implicit. var result = from PersonEntity p in PersonEntity.Queryable where p.Name == (Name)"Thomas" select p; return result.First(); //Now works

    Read the article

  • I do I iterate the records in a database using LINQ when I have already built the LINQ DB code?

    - by Seth Spearman
    I asked on SO a few days ago what was the simplest quickest way to build a wrapper around a recently completed database. I took the advice and used sqlmetal to build linq classes around my database design. Now I am having two problems. One, I don't know LINQ. And, two, I have been shocked to realize how hard it is to learn. I have a book on LINQ (Linq In Action by Manning) and it has helped some but at the end of the day it is going to take me a couple of weeks to get traction and I need to make some progress on my project today. So, I am looking for some help getting started. Click HERE To see my simple database schema. Click HERE to see the vb class that was generated for the schema. My needs are simple. I have a console app. The main table is the SupplyModel table. Most of the other tables are child tables of the SupplyModel table. I want to iterate through each of Supply Model records. I want to grab the data for a supply model and then DoStuff with the data. And I also need to iterate through the child records, for each supply model, for example the NumberedInventories and DoStuff with that as well. I want to only iterate the SupplyModels that are have IDs that are in an array of strings containing the IDs. I need help doing this in VB rather than C# if possible. Thanks for your help. Seth

    Read the article

  • Converting a Linq expression tree that relies on SqlMethods.Like() for use with the Entity Framework

    - by JohnnyO
    I recently switched from using Linq to Sql to the Entity Framework. One of the things that I've been really struggling with is getting a general purpose IQueryable extension method that was built for Linq to Sql to work with the Entity Framework. This extension method has a dependency on the Like() method of SqlMethods, which is Linq to Sql specific. What I really like about this extension method is that it allows me to dynamically construct a Sql Like statement on any object at runtime, by simply passing in a property name (as string) and a query clause (also as string). Such an extension method is very convenient for using grids like flexigrid or jqgrid. Here is the Linq to Sql version (taken from this tutorial: http://www.codeproject.com/KB/aspnet/MVCFlexigrid.aspx): public static IQueryable<T> Like<T>(this IQueryable<T> source, string propertyName, string keyword) { var type = typeof(T); var property = type.GetProperty(propertyName); var parameter = Expression.Parameter(type, "p"); var propertyAccess = Expression.MakeMemberAccess(parameter, property); var constant = Expression.Constant("%" + keyword + "%"); var like = typeof(SqlMethods).GetMethod("Like", new Type[] { typeof(string), typeof(string) }); MethodCallExpression methodExp = Expression.Call(null, like, propertyAccess, constant); Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(methodExp, parameter); return source.Where(lambda); } With this extension method, I can simply do the following: someList.Like("FirstName", "mike"); or anotherList.Like("ProductName", "widget"); Is there an equivalent way to do this with Entity Framework? Thanks in advance.

    Read the article

  • Order by descending is not working on LINQ to Entity

    - by Vinni
    Order by descending is not working on LINQ to Entity In the following Query In place of ascending If I keep descending it is not working. Please help me out var hosters = from e in context.Hosters_HostingProviderDetail where e.ActiveStatusID == pendingStateId orderby e.HostingProviderName ascending select e; return hosters.ToList();

    Read the article

  • C# & ASP.Net - determine linq query generation time

    - by Chris Klepeis
    I'd like to detemine the amount of time it takes for my ASP.Net program to generate certain sql queries using linq.... note - I want the query generation time, not the query execution time. Is this possible, or even feasable (if its usually fast)? My website has some heavy traffic and I want to cover all of my bases.

    Read the article

  • LINQ TO SQL, Dynamic query with DATE type fields

    - by acanthus
    Hello, I'm building a query with the LINQ dynamic library so I don't know how many potential parameters will I have and I get an error when trying to query DATE type fields: Operator '=' incompatible with operand types 'DateTime' and 'String' When I step through the debugger in the Dynamic.cs it shows that the value is of type string and the field is of type date so the problem is obvious but I have no idea how to approach it. Any ideas? BR

    Read the article

  • Simpler Linq to XML queries with the DLR

    - by Xavier
    Hi folks, I have a question regarding Linq to XML queries and how we could possibly make them more readable using the new dynamic keyword. At the moment I am writing things like: var result = from p in xdoc.Elements("product") where p.Attribute("type").Value == "Services" select new { ... } What I would like to write is something like: var result = from p in xdoc.Products where p.Type == "Services" select new { ... } I know I can do this with Linq to XSD which is pretty good already, but obviously this requires an XSD schema and I don't always have one. I am sure there should be a way to achieve this using the new dynamic features of .NET 4.0 but I'm not sure how or if anyone already had a go at this. Obviously I would loose some of the advantages of Linq to XSD (typed members and compile time checks) but it wouldn't be worse than the original solution and would certainly be more readable. Anyone has an idea? Thanks

    Read the article

  • Need to debug LINQ simple queries in Visual Studio 2010

    - by maxima120
    I often get in a position when I need to know why my LINQ doesnt work as intended... I use object collections and extensions. I dont want spend more than couple of minutes on it. LINQ supposed to make developer's life easier not harder. I hoped VS 2010 will have it fixed but I now use RC and it still doesnt let me type LINQ and check what is going on... Says as before "Expression cannot contain lambda expressions"... Is there some add-on for Visual Studio so I can quickly and effectively run ad-hoc queries and find out what is going on and where I am wrong?

    Read the article

  • Order by descending based on condition

    - by Vinni
    Hello All, I want to write a LINQ to Entity query which does order by ascending or descending based on input parameter, Is there any way for that. Following is the my code. Please suggest. public List<Hosters_HostingProviderDetail> GetPendingApproval(SortOrder sortOrder) { List<Hosters_HostingProviderDetail> returnList = new List<Hosters_HostingProviderDetail>(); int pendingStateId = Convert.ToInt32(State.Pending); //If the sort order is ascending if (sortOrder == SortOrder.ASC) { var hosters = from e in context.Hosters_HostingProviderDetail where e.ActiveStatusID == pendingStateId orderby e.HostingProviderName ascending select e; returnList = hosters.ToList<Hosters_HostingProviderDetail>(); return returnList; } else { var hosters = from e in context.Hosters_HostingProviderDetail where e.StateID == pendingStateId orderby e.HostingProviderName descending select e; returnList = hosters.ToList<Hosters_HostingProviderDetail>(); return returnList; } }

    Read the article

  • Linq to NHibernate, Order by Rand() ?

    - by Felipe
    Hi everybody, I'm using Linq To Nhibernate, and with a HQL statement I can do something like this: string hql = "from Entity e order by rand()"; Andi t will be ordered so random, and I'd link to know How can I do the same statement with Linq to Nhibernate ? I try this: var result = from e in Session.Linq<Entity> orderby new Random().Next(0,100) select e; but it throws a exception and doesn't work... is there any other way or solution? Thanks Cheers

    Read the article

  • Querying a Single Column with LINQ

    - by Hossein Margani
    Hi Every one! I want to fetch array of values of a single column in a table, for example, I have a table named Customer(ID,Name), and want to fetch ids of all customers. my query in LINQ is: var ids = db.Customers.Select(c=>c.ID).ToList(); The answer of this query is correct, but I ran SQL Server Profiler, and saw the query which was like this: SELECT [t0].[ID], [t0].[Name] FROM [dbo].[Customer] AS [t0] I understood that LINQ selects all columns and then creates the integer array of ID fields. How can I write a LINQ query which generates this query in SQL Server: SELECT [t0].[ID] FROM [dbo].[Customer] AS [t0] Thank you.

    Read the article

  • NHibernate Linq - Duplicate Records

    - by adegiamb
    I am having a problem with duplicate blog post coming back when i run the linq statement below. The issue that a blog post can have the same tag more then once and that's causing the problem. I know when you use criteria you can do the followingcriteria.SetResultTransformer(new DistinctRootEntityResultTransformer()); How can I do the same thing with linq? List<BlogPost> result = (from blogPost in _session.Linq<BlogPost>() from tags in blogPost.Tags where tags.Tag == tag && blogPost.IsPublished && blogPost.Slug != slugToExclude orderby blogPost.DateCreated descending select blogPost).Distinct() .Skip(recordsToSkip).Take(pageSize).ToList();

    Read the article

  • LINQ expression precedence with Skip(), Take() and OrderBy()

    - by Robert Koritnik
    I'm using LINQ to Entities and display paged results. But I'm having issues with the combination of Skip(), Take() and OrderBy() calls. Everything works fine, except that OrderBy() is assigned too late. It's executed after result set has been cut down by Skip() and Take(). So each page of results has items in order. But ordering is done on a page handful of data instead of ordering of the whole set and then limiting those records with Skip() and Take(). How do I set precedence with these statements? My example (simplified) var query = ctx.EntitySet.Where(/* filter */).OrderBy(/* expression */); int total = query.Count(); var result = query.Skip(n).Take(x).ToList();

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >