Search Results

Search found 39 results on 2 pages for 'defaultifempty'.

Page 1/2 | 1 2  | Next Page >

  • Defaultifempty seems to work in linq to entities

    - by Rand
    I'm new to linq and linq to entities so I might have gone wrong in my assumptions, but I've been unknowingly trying to use DefaultIfEmpty in L2E. For some reason if I turn the resultset into a List, the Defaultifempty() works I don't know if I've inadvertantly crossed over into Linq area. The code below works, can anyone tell me why? And if it does work great, then it'll be of help to other people. var results = (from u in rv.tbl_user .Include("tbl_pics") .Include("tbl_area") .Include("tbl_province") .ToList() where u.tbl_province.idtbl_Province == prov select new { u.firstName, u.cellNumber, u.tbl_area.Area, u.ID,u.tbl_province.Province_desc, pic = (from p3 in u.tbl_pics where p3.tbl_user.ID == u.ID select p3.pic_path).DefaultIfEmpty("defaultpic.jpg").First() }).ToList();

    Read the article

  • DefaultIfEmpty doesn't work

    - by Freshblood
    Why is array still null after queried by DefaultIfEmpty ? class Program { static void Main(string[] args) { Program[] array = new Program[5]; Program[] query = array.DefaultIfEmpty(new Program()).ToArray(); foreach (var item in query) { Console.WriteLine(item.ToString()); } Console.ReadKey(); } }

    Read the article

  • LINQ DefaultIfEmpty(), generating inferred argument error

    - by Refracted Paladin
    I am trying to get the below linq query to return -1 if there isn't any current value. I was looking at this article on MSDN, here, and it seemed that DefaultIfEmpty() was what I wanted. Unfortunately, I am getting a The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly. error. I guess I am not sure what that means or what it is telling me to do. Can someone explain, please. public static int CheckForDRIID(int personID) { using (var context = ConnectDataContext.Create()) { var masterIndex = (from applicationAssociation in context.tblApplicationAssociations where applicationAssociation.ApplicationID == 1 && applicationAssociation.PersonID == personID select applicationAssociation.PersonApplicationID).DefaultIfEmpty(-1).Single(); return Convert.ToInt32(masterIndex); } }

    Read the article

  • Using DefaultIfEmpty in Linq - problem substituting a null value for a default value

    - by FiveTools
    I have questions that may or may not have a question_group if all the questions do not have a question_group and if I use default if empty like this: question_group defaultQuestion = new question_group {question_group_id = Guid.Empty}; questions.Select(x => x.question_group).DefaultIfEmpty(defaultQuestion).Distinct(); shouldn't I get an IEnumerable<question_group> containing only the default question_group that I defined? I get null.... what am I missing here?

    Read the article

  • Linq, Left Join and Dates...

    - by BitFiddler
    So my situation is that I have a linq-to-sql model that does not allow dates to be null in one of my tables. This is intended, because the database does not allow nulls in that field. My problem, is that when I try to write a Linq query with this model, I cannot do a left join with that table anymore because the date is not a 'nullable' field and so I can't compare it to "Nothing". Example: There is a Movie table, {ID,MovieTitle}, and a Showings table, {ID,MovieID,ShowingTime,Location} Now I am trying to write a statement that will return all those movies that have no showings. In T.SQL this would look like: Select m.* From Movies m Left Join Showings s On m.ID = s.MovieID Where s.ShowingTime is Null Now in this situation I could test for Null on the 'Location' field but this is not what I have in reality (just a simplified example). All I have are non-null dates. I am trying to write in Linq: From m In dbContext.Movies _ Group Join s In Showings on m.ID Equals s.MovieID into MovieShowings = Group _ From ms In MovieShowings.DefaultIfEmpty _ Where ms.ShowingTime is Nothing _ Select ms However I am getting an error saying 'Is' operator does not accept operands of type 'Date'. Operands must be reference or nullable types. Is there any way around this? The model is correct, there should never be a null in the Showings:ShowTime table. But if you do a left join, and there are no show times for a particular movie, then ShowTime SHOULD be Nothing for that movie... Thanks everyone for your help.

    Read the article

  • Fixing LINQ Error: Sequence contains no elements

    - by ChrisD
    I’ve read some posts regarding this error when using the First() or Single() command.   They suggest using FirstOrDefault() or SingleorDefault() instead. But I recently encountered it when using a Sum() command in conjunction with a Where():   Code Snippet var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).Max(p => p.Amount);   When the Where() function eliminated all the items in the policies collection, the Sum() command threw the “Sequence contains no elements” exception.   Inserting the DefaultIfEmpty() command between the Where() and Sum(), prevents this error: Code Snippet var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).DefaultIfEmpty().Max(p => p.Amount);   but now throws a Null Reference exception!   The Fix: Using a combination of DefaultIfEmpty() and a null check in the Sum() command solves this problem entirely: Code Snippet var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).DefaultIfEmpty().Max(p =>  p==null?0 :p.Amount);

    Read the article

  • Linq Left Outer Join

    - by Neil
    I am new to LINQ and am trying to convert a SQL query to LINQ: SQL: left outer join PRODUCT_BEST_USE pbu on pbu.PRODUCT_GUID = @uProductId and pbu.BEST_USE_GUID = bu.BEST_USE_GUID LINQ: from PBU in PRODUCT_BEST_USE.Where(PBU=>PBU.PRODUCT_GUID == p.PRODUCT_GUID).DefaultIfEmpty() When I add and PBU.BEST_USE_GUID equals BU.BEST_USE_GUID, I get an error: "A query body must end with a select clause or a group clause" Here is the full Linq query: from p in PRODUCT join BU in BEST_USE on p.CATEGORY_GUID equals BU.CATEGORY_GUID from PBU in PRODUCT_BEST_USE.Where(PBU=>PBU.PRODUCT_GUID == p.PRODUCT_GUID).DefaultIfEmpty() and PBU.BEST_USE_GUID equals BU.BEST_USE_GUID where p.PRODUCT_GUID == new Guid("d317752b-581d-4f43-92fa-4a4af91009f5") select new { BU.NAME, PBU.PRODUCT_BEST_USE_GUID }

    Read the article

  • Joins in LINQ to SQL

    - by rajbk
    The following post shows how to write different types of joins in LINQ to SQL. I am using the Northwind database and LINQ to SQL for these examples. NorthwindDataContext dataContext = new NorthwindDataContext(); Inner Join var q1 = from c in dataContext.Customers join o in dataContext.Orders on c.CustomerID equals o.CustomerID select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0]INNER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID] Left Join var q2 = from c in dataContext.Customers join o in dataContext.Orders on c.CustomerID equals o.CustomerID into g from a in g.DefaultIfEmpty() select new { c.CustomerID, c.ContactName, a.OrderID, a.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID] AS [OrderID], [t1].[OrderDate] AS [OrderDate]FROM [dbo].[Customers] AS [t0]LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID] Inner Join on multiple //We mark our anonymous type properties as a and b otherwise//we get the compiler error "Type inferencce failed in the call to 'Join’var q3 = from c in dataContext.Customers join o in dataContext.Orders on new { a = c.CustomerID, b = c.Country } equals new { a = o.CustomerID, b = "USA" } select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0]INNER JOIN [dbo].[Orders] AS [t1] ON ([t0].[CustomerID] = [t1].[CustomerID]) AND ([t0].[Country] = @p0) Inner Join on multiple with ‘OR’ clause var q4 = from c in dataContext.Customers from o in dataContext.Orders.Where(a => a.CustomerID == c.CustomerID || c.Country == "USA") select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0], [dbo].[Orders] AS [t1]WHERE ([t1].[CustomerID] = [t0].[CustomerID]) OR ([t0].[Country] = @p0) Left Join on multiple with ‘OR’ clause var q5 = from c in dataContext.Customers from o in dataContext.Orders.Where(a => a.CustomerID == c.CustomerID || c.Country == "USA").DefaultIfEmpty() select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID] AS [OrderID], [t1].[OrderDate] AS [OrderDate]FROM [dbo].[Customers] AS [t0]LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON ([t1].[CustomerID] = [t0].[CustomerID]) OR ([t0].[Country] = @p0)

    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

  • Left outer join null using VB.NET and LINQ

    - by jvcoach23
    I've got what I think is a working left outer join LINQ query, but I'm having problems with the select because of null values in the right hand side of the join. Here is what I have so far Dim Os = From e In oExcel Group Join c In oClassIndexS On c.tClassCode Equals Mid(e.ClassCode, 1, 4) Into right1 = Group _ From c In right1.DefaultIfEmpty I want to return all of e and one column from c called tClassCode. I was wondering what the syntax would be. As you can see, I'm using VB.NET. Update... Here is the query doing join where I get the error: _message = "Object reference not set to an instance of an object." Dim Os = From e In oExcel Group Join c In oClassIndexS On c.tClassCode Equals Mid(e.ClassCode, 1, 4) Into right1 = Group _ From c In right1.DefaultIfEmpty Select e, c.tClassCode If I remove the c.tClassCode from the select, the query runs without error. So I thought perhaps I needed to do a select new, but I don't think I was doing that correctly either.

    Read the article

  • Types in Union or Concat cannot be constructed with hierarchy

    - by user927777
    I am trying to run a query very similar to the following: (from bs in DataContext.TblBookShelf join b in DataContext.Book on bs.BookID equals b.BookID where bs.BookShelfID == bookShelfID select new BookItem { Categories = String.Join("<br/>", b.BookCategories.Select(x => x.Name).DefaultIfEmpty().ToArray()), Name = b.Name, ISBN = b.ISBN, BookType = "Shelf" }).Union(from bs in DataContext.TblBookShelf join bi in DataContext.TblBookInventory on bs.BookID equals bi.BookID select new BookItem { Categories = String.Join("<br/>", bi.BookCategories.Select(x => x.Name).DefaultIfEmpty().ToArray()), Name = bi.Name, ISBN = bi.ISBN, BookType = "Inventory" }); I am receiving "Types in Union or Concat cannot be constructed with hierarchy" after the statement executes, I need to to be able to get a list of categories to display with each book. If anyone could shed some light on a possible solution, it would be greatly appreciated.

    Read the article

  • Working with Joins in LINQ

    - by vik20000in
    While working with data most of the time we have to work with relation between different lists of data. Many a times we want to fetch data from both the list at once. This requires us to make different kind of joins between the lists of data. LINQ support different kinds of join Inner Join     List<Customer> customers = GetCustomerList();     List<Supplier> suppliers = GetSupplierList();      var custSupJoin =         from sup in suppliers         join cust in customers on sup.Country equals cust.Country         select new { Country = sup.Country, SupplierName = sup.SupplierName, CustomerName = cust.CompanyName }; Group Join – where By the joined dataset is also grouped.     List<Customer> customers = GetCustomerList();     List<Supplier> suppliers = GetSupplierList();      var custSupQuery =         from sup in suppliers         join cust in customers on sup.Country equals cust.Country into cs         select new { Key = sup.Country, Items = cs }; We can also work with the Left outer join in LINQ like this.     List<Customer> customers = GetCustomerList();     List<Supplier> suppliers = GetSupplierList();      var supplierCusts =         from sup in suppliers         join cust in customers on sup.Country equals cust.Country into cs         from c in cs.DefaultIfEmpty()  // DefaultIfEmpty preserves left-hand elements that have no matches on the right side         orderby sup.SupplierName         select new { Country = sup.Country, CompanyName = c == null ? "(No customers)" : c.CompanyName,                      SupplierName = sup.SupplierName};Vikram

    Read the article

  • LINQ to SQL - Left Outer Join with multiple join conditions

    - by dan
    I have the following SQL which I am trying to translate to LINQ: SELECT f.value FROM period as p LEFT OUTER JOIN facts AS f ON p.id = f.periodid AND f.otherid = 17 WHERE p.companyid = 100 I have seen the typical implementation of the left outer join (ie. into x from y in x.DefaultIfEmpty() etc.) but am unsure how to introduce the other join condition ('AND f.otherid = 17') EDIT Why is the 'AND f.otherid = 17' condition part of the JOIN instead of in the WHERE clause? Because f may not exist for some rows and I still want these rows to be included. If the condition is applied in the WHERE clause, after the JOIN - then I don't get the behaviour I want. Unfortunately this: from p in context.Periods join f in context.Facts on p.id equals f.periodid into fg from fgi in fg.DefaultIfEmpty() where p.companyid == 100 && fgi.otherid == 17 select f.value seems to be equivalent to this: SELECT f.value FROM period as p LEFT OUTER JOIN facts AS f ON p.id = f.periodid WHERE p.companyid = 100 && AND f.otherid = 17 which is not quite what I'm after.

    Read the article

  • Is there an efficient way in LINQ to use a contains match if and only if there is no exact match?

    - by Peter
    I have an application where I am taking a large number of 'product names' input by a user and retrieving some information about each product. The problem is, the user may input a partial name or even a wrong name, so I want to return the closest matches for further selection. Essentially if product name A exactly matches a record, return that, otherwise return any contains matches. Otherwise return null. I have done this with three separate statements, and I was wondering if there was a more efficient way to do this. I am using LINQ to EF, but I materialize the products to a list first for performance reasons. productNames is a List of product names (input by the user). products is a List of product 'records' var directMatches = (from s in productNames join p in products on s.ToLower() equals p.name.ToLower() into result from r in result.DefaultIfEmpty() select new {Key = s, Product = r}); var containsMatches = (from d in directMatches from p in products where d.Product == null && p.name.ToLower().Contains(d.Key) select new { d.Key, Product = p }); var matches = from d in directMatches join c in containsMatches on d.Key equals c.Key into result from r in result.DefaultIfEmpty() select new {d.Key, Product = d.Product ?? (r != null ? r.Product: null) };

    Read the article

  • Left Join in Subsonic3

    - by muek
    Hi there, I'm new in subsonic3, and I'm getting some errors when I try to use LeftJoin var q = from c in categories join p in products on c equals p.Category into ps from p in ps.DefaultIfEmpty() select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName }; The error is "System.Collections.Generic.Enumerable '...' cannot be used for parameter of type System.Linq.IQueryable Does anyone had this error before? Did you fix it? Thanks

    Read the article

  • *Right* outer join in LINQ

    - by Rap
    Is it safe to say that there is no such thing as a right outer join in LINQ? I know to effectively create one, you'd just swap the tables in a left outer join. But can you apply the DefaultIfEmpty() method to the table on the left side of the equijoin to make it a right outer join?

    Read the article

  • Three level heirarchal data-linq

    - by user326010
    Hi I have three level heirarchal data. using the statement below i managed to display two level data. I need to extend it to one more level. Current heirachy is Modules--Documents I need to extend it as Packages--Modules--Documents var data = (from m in DataContext.SysModules join d in DataContext.SysDocuments on m.ModuleID equals d.ModuleID into tempDocs from SysDocument in tempDocs.DefaultIfEmpty() group SysDocument by m).ToList(); Regards Tassadaque

    Read the article

  • LINQ to SQL left outer joins

    - by César
    Is this query equivalent to a LEFT OUTER join? var rows = from a in query join s in context.ViewSiteinAdvise on a.Id equals s.SiteInAdviseId where a.Order == s.Order select new {....}; I tried this but it did not result from s in ViewSiteinAdvise join q in query on s.SiteInAdviseId equals q.Id into sa from a in sa.DefaultIfEmpty() where s.Order == a.Order select new {s,a} I need all columns from View

    Read the article

  • Left outer join in LINQ is showing exception

    - by stackuser3
    The folloqing is the excpetion I am getting The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type. below is my LINQ Statement where QuestionId is the primary key in my table var questionViewsData = from questionViews in objDc.SC_QuestionsViews join questions in objDc.SC_Questions on questionViews.QuestionId equals questions.QuestionId into qs from questions in qs.DefaultIfEmpty() where questionViews.CreatedDate.Date == new DateTime(2010, 4,27) select new { Selected =(questions == null ?-1:questions.QuestionId), QuestioinTitle = questions.Title, VotesCount = questions.VotesCount }; Let me know how to resolve this

    Read the article

  • ordering by a property on a joined table linq to sql

    - by Gazeth
    I have the following linq query from o in context.Opportunities join i in context.Interactions on o.OpportunityID equals i.OpportunityID into ints from i in ints.DefaultIfEmpty() orderby i.StatusID descending, o.StatusID descending select o Now i want to then do a distinct on the opportunities table but doing so removes my orderby. I know that you can do Distinct().OrderBy but how do i get a reference to the interactions table that was joined when I'm only selecting the opportunity entity?

    Read the article

  • Outer Join is not working in Linq Query: The method 'Join' cannot follow the method 'SelectMany' or is not supported

    - by Scorpion
    I am writing the Linq query as below: But on run its throwing the following error: The method 'Join' cannot follow the method 'SelectMany' or is not supported. Try writing the query in terms of supported methods or call the 'AsEnumerable' or 'ToList' method before calling unsupported methods. LINQ from a in AccountSet join sm in new_schoolMemberSet on a.AccountId equals sm.new_OrganisationId.Id into ps from suboc in ps.DefaultIfEmpty() join sr in new_schoolRoleSet on suboc.new_SchoolRoleId.Id equals sr.new_schoolRoleId where sr.new_name == "Manager" where a.new_OrganisationType.Value == 430870007 select new { a.AccountId, a.new_OrganisationType.Value } I am expecting the result as below: I never used the Outer join in Linq before. So please correct me if I am doing it wrong. Thanks

    Read the article

  • Left Join in Subsonic 3

    - by user303187
    I'm trying to do a left join in subsonic 3 using linq but it doesn't seem to work, I get a big error. var post = from p in Post.All() join q in Quote.All() on p.ID equals q.PostID into pq where p.ID == id.Value from qt in pq.DefaultIfEmpty() select new {p, qt}; I'm using subsonic 3, latest GIT version from Rob, but I'm getting an error, see below, when I try a left join. I have searched but I didn't found any solution. Can anyone explain to me why the error and how to fix it? Thanks Expression of type 'System.Collections.Generic.IEnumerable1[GetAQuote.Post]' cannot be used for parameter of type 'System.Linq.IQueryable1[GetAQuote.Post]' of method 'System.Linq.IQueryable1[<>f__AnonymousType221[GetAQuote.Post], System.Collections.Generic.IEnumerable1%5BGetAQuote.Quote%5D, System.Linq.Expressions.Expression1[System.Func2%5BGetAQuote.Post,System.Int32%5D%5D, System.Linq.Expressions.Expression1[System.Func2%5BGetAQuote.Quote,System.Int32%5D%5D, System.Linq.Expressions.Expression1[System.Func3%5BGetAQuote.Post,System.Collections.Generic.IEnumerable1[GetAQuote.Quote],<>f__AnonymousType22%5BGetAQuote.Post,System.Collections.Generic.IEnumerable1%5BGetAQuote.Quote%5D%5D%5D%5D"GetAQuote.Post,System.Collections.Generic.IEnumerable1[GetAQuote.Quote]]] GroupJoin[Post,Quote,Int32,<f__AnonymousType22'`

    Read the article

  • LINQ, Left Join, Only Get where null in join table

    - by kmehta
    Hi. I am trying to do a left outer join on two tables, but I only want to return the results from the first table where the second table does not have a record (null). var agencies = from a in agencyList join aa in joinTable on a.AgencyId equals aa.AgencyId into joined from aa in joined.DefaultIfEmpty() where aa == null) select a; But this does not exclude the non null values of aa, and returns all the records just the same as if the 'where aa == null' was not there. Any help is appreciated. Thanks.

    Read the article

  • Linq To Sql Left outer join - filtering null results

    - by Harry
    I'd like to reproduce the following SQL into C# LinqToSql SELECT TOP(10) Keywords.* FROM Keywords LEFT OUTER JOIN IgnoreWords ON Keywords.WordID = IgnoreWords.ID WHERE (DomainID = 16673) AND (IgnoreWords.Name IS NULL) ORDER BY [Score] DESC The following C# Linq gives the right answer. But I can't help think I'm missing something (a better way of doing it?) var query = (from keyword in context.Keywords join ignore in context.IgnoreWords on keyword.WordID equals ignore.ID into ignored from i in ignored.DefaultIfEmpty() where i == null where keyword.DomainID == ID orderby keyword.Score descending select keyword).Take(10); the SQL produced looks something like this: SELECT TOP (10) [t0].[DomainID], [t0].[WordID], [t0].[Score], [t0].[Count] FROM [dbo].[Keywords] AS [t0] LEFT OUTER JOIN (SELECT 1 AS [test], [t1].[ID] FROM [dbo].[IgnoreWords] AS [t1]) AS [t2] ON [t0].[WordID] = [t2].[ID] WHERE ([t0].[DomainID] = 16673) AND ([t2].[test] IS NULL) ORDER BY [t0].[Score] DESC How can I get rid of this redundant inner selection? It's only slightly more expensive but every bit helps!

    Read the article

1 2  | Next Page >