Questions tagged [linq]

33500 questions
1

votes
2

answer
88

Views

Which Linq join will work for my scenario, confused

I have a web api project. In database I have two tables of comments and pictures. I want to use join to merge these two tables in such a way that every picture should have all the comments related to it. Both tables have picture id. Which join should I use? I need to use linq. Can someone tell me...
Obvious
1

votes
1

answer
792

Views

In constructors and initializers, only property or field parameter bindings are supported in LINQ to Entities

I am able to execute the below code snippet in my application with no problem. Projects.Select(s => new ProjectName() { ProjectID = s.ProjectID, Name = s.Name }) Note that ProjectName is a parameterless constructor which exists in the following class: namespace YeagerTechModel.DropDownLists { [Dat...
sagesky36
0

votes
0

answer
21

Views

Merging rows with negative values in datatable

I know there are might be many answers to the title, but my case is a little different. I've been trying to achieve the following, but I got stuck with my Linq. Any help would be much appreciated. I have 3 columns in Datatable1 as shown below. Item Quantity Store ItemA 12 S...
Wildchild
0

votes
0

answer
5

Views

Is StructureMap Performing Unsolicited Database Calls?

I inherited a ASP.Net MVC project & augmented with some new Entity Framework entities....I also added some IoC using StructureMap. I am using... Microsoft.AspNet.Mvc 5.2.6 EntityFramework 6.2.0 StructureMap 4.7.0 THE PROBLEM When I execute an MVC Action that uses any of my 'Complex' View Models I su...
Prisoner ZERO
1

votes
1

answer
635

Views

Doing Sum() on a set of anonymous type: is it possible?

If I select an anonymous type (select new) from a query: var smsPerGroup = from g in db.Groups select new { GroupName = g.Name, ReceivedSMS = g.Members.SelectMany(p => p.ReceivedSMS).Count() }; It happends that I can't sum() on it: int max = smsPerGroup.Max(g => g.ReceivedSMS); // ERROR! The error...
sports
1

votes
2

answer
5.1k

Views

Multiple Include and Where Clauses Linq

I have a database where I'm wanting to return a list of Clients. These clients have a list of FamilyNames. I started with this var query = DbContext.Clients.Include(c => c.FamilyNames).ToList() //returns all clients, including their FamilyNames...Great. But I want somebody to be able to search for a...
James
1

votes
1

answer
457

Views

Linq ToArray in ToArray error

I'm trying to make a array of my model (Basket) with Linq and in that model i have another array, so when i'm creating that model with link i got this error: An error has occurred. LINQ to Entities does not recognize the method 'HTTP.Webshop.API.WebAPI.Models.BasketLine[] ToArray[BasketLine](System....
jfamvg
1

votes
2

answer
103

Views

Returning null if multiple instances are found

I have an IEnumerable and a predicate (Func) and I am writing a method that shall return a value if only one instance in the list matches the predicate. If the criteria is matched by none, then none was found. If the criteria is matched by many instances, then the predicate was insufficient to succe...
Tormod
1

votes
4

answer
850

Views

select data more than 365 days old in linq

This is my Table structure t_physical_inventory dte_cycle_count | qty | location i am using the following Linq query to get result int number = 3; List Location = (from c in dc.t_physical_inventories where (c.dte_cycle_count == null || ((TimeSpan)(Convert.ToDateTime(c.dte_cycle_count) - (DateTime.No...
Sunny
1

votes
1

answer
2.6k

Views

ASP.NET MVC Select list value using key

I am still reasonably new to C# and trying to understand list objects. I have a list object with key/value pairs in it, populated from a database (that part is working). I then want to select a value from that list, using the 'key'. From what I have read I think Linq might be the best way to do thi...
Jake
1

votes
2

answer
568

Views

Two db contexts under TransactionScope fails

I am stuck using two db connections with entity framework contexts under a single transaction. I am trying to use two db contexts under one transaction scope. I get "MSTDC not available". I read it's not an EF problem it's TDC which does not allow two connections. Is there any answer for this proble...
bgS
1

votes
1

answer
89

Views

Find difference from IList<string[]> one and IList<string[]> two using Linq operation

Hi is there any build in method using Linq or lambda expression or any other approach we can get records which is present and in IList one but not in IList two or vise versa. I tried with linq Except keyword but its not working, it's working perfect when I am doing operation on string[] not on IList...
Nitesh
1

votes
1

answer
2.1k

Views

C# JSON.Net parse and get list of all elements matching a value using LINQ

I'm having trouble finding the correct method for getting a list of json arrays from JObject. _name element inside the array should be equal to foo. This is the sample json: { "doc": [{ "bob": [{ "tom": [{ "frank": [{ "category": [{ "_name": "foo", "letters": "abc" }, { "_name": "foo", "letters": "d...
VixinG
1

votes
1

answer
531

Views

Use SQL 2012 FORMAT function with LINQ to Entity Framework

I would like to add the built in SQL 2012 FORMAT function to a static function class to use with LINQ to Entity Framework. I followed this source code to mimic adding a built in SQL function. public static class ExtendSqlFunctions { [DbFunction("SqlServer", "FORMAT")] public static string Form...
goroth
0

votes
0

answer
20

Views

Add user role from identity to custom database

I have a function that finds a user in a database and adds a role. The role is added in the Asp.net identity table. I am trying to update the role that also exists in another table in a different database. I've written the logic but I'm not quite there yet. So my question is, how do I correctly add...
Chris H.
1

votes
1

answer
1.1k

Views

IQueryable Expression Translation

I am creating an IQueryable that I want to use for a query passed to entity framework. My repository does not expose queryable. var query = new List().AsQueryable().Where(x => x.Property == "argument"); I have a method on my repository that will take in an IQueryable. How do I query my DbSet with...
twifosp
1

votes
1

answer
1.6k

Views

How to replace null with Empty string in Expressions.Expression in c# Linq

I am new to linq c# , Following is my function public static IQueryable BuildWhereExpression(this IQueryable query, SearchAttributes searchModel) { string FilterField = searchModel.FilterField; string FilterOperator = searchModel.FilterOperator; string FilterValue = searchModel.FilterValue; Paramete...
Mayank
1

votes
2

answer
99

Views

SQL statement convert in LINQ

I have a Products table and OrdersDetails table. I want to display top 5 products by order count. This is my SQL statement that I want to convert in LINQ: SELECT TOP 5 P.ProductId, COUNT(OD.OrderId) AS 'Quantity Ordered' FROM Products AS P INNER JOIN OrdersDetails AS OD ON P.ProductId = OD.ProductI...
dondomates
1

votes
4

answer
52

Views

Distinct rows from db table with unique IDs but same names

I am creating a videorental system and I'm told that there are to be multiple entries of the same movie, as in a real videostore, but they should all have unique IDs. I'm using LINQ to fetch the data, and currently my view shows me the entire table, so the same movie name gets repeated alot. I tried...
David
1

votes
1

answer
80

Views

EF 6.x Code First: Different SQL Generated for Navigation Property

I'm a veteran web developer with plenty of T-SQL and schema designing experience, but, fairly new to EF (skipping right to EF 6!). I'm wondering what's wrong with my POCOs that I'm getting different SQL generated for the following two queries. Basically, I have two objects, "Parent" and "ChildThing"...
bkwdesign
1

votes
2

answer
991

Views

Get the longest string from List<Class> using LINQ C#

What is the fastest way to get the length of the longest string in name for the following List: public class test { public int id { get; set; } public string name { get; set; } } List l = new List(); Using LINQ.
astralmaster
1

votes
2

answer
493

Views

Sort Array of Objects by Date

I am using jLinq to query an Array of Objects this is my Array of Objects: wo: [{ ID: 1, 'CreatedYM': '2015-Jun'}, { ID: 2, 'CreatedYM': '2014-May'}, { ID: 3, 'CreatedYM': '2015-Jan'}, { ID: 4, 'CreatedYM': '2015-Aug'}, { ID: 5, 'CreatedYM': '2014-Dec'}] this is my query: jlinq.from( wo ).group...
Lugarini
1

votes
3

answer
890

Views

C# Prime Numbers with LINQ

I am interested with LINQ these days. I am trying to get prime numbers. I am actually did very well but my code doesn't show primes which is below Sqrt(n). static void Main(string[] args) { Func EnumerableRange = (startPoint, endPoint) => Enumerable.Range(Math.Min(startPoint, endPoint), Math.Abs(sta...
Artxzta
1

votes
2

answer
1.4k

Views

Eager Loading with Entity Framework, LINQ

I am working on ASP.NET MVC project. i am using EF code-first approach. i have 3 classes, which are: public class A { public int AID {get;set;} public string A1 {get;set} public string A2 {get;set} public virtual List Bs {get;set;} } public class B { public int BID {get;set;} public string B1 {get;s...
Willie
1

votes
0

answer
22

Views

How to optimize (or rewrite from scratch) complicated query having query_cost ~40k ? (sub-queries, joins, group by, order by)

I am stuck with 'infinite' execution of query on mysql. Its query_cost are really high. Query contains aggregations and filters. Imagine I have two tables: create table trades ( TICKET int not null primary key, LOGIN int not null, SYMBOL char(16...
1

votes
1

answer
878

Views

Linq Expression to handle null

I am trying to use the following code in a linq expression, which I found at this question However it fails if the database field is null. public static IQueryable FieldsAreEqualOrBothNullOrEmpty( this IQueryable source, Expression member, string value) { Expression body; if (string.IsNullOrEmpty(v...
Kirsten Greed
1

votes
1

answer
71

Views

Iterate with LINQ over a list and set founded varible [duplicate]

This question already has an answer here: LINQ equivalent of foreach for IEnumerable 21 answers I have this code and want to do the same with a linq statement. foreach (var field in fieldExtension) { if (field.Name.Equals(item.Name)) { field.Access = true; } } It is easy to iterate over the list wi...
Florin M
0

votes
2

answer
34

Views

More than one record is updated EF-Linq C#

I have the following table: I have several arrays, where I will scroll if the data match to decrease its amount: //DISMINUYE CANTIDAD DE CASILLER public void disminuyeCasiller(string[] codParte, string [] rolls, double[] cantResta) { int size = codParte.Length; for(int i = 0; i < size; i++) { string...
Baker1562
0

votes
0

answer
29

Views

C# Linq equivalent for SQL script not responding

I have the following SQL script which works fine and pretty fast: select top 30 CONVERT(date, p.DateCreated) as Fecha, (select count(*) from People d where d.recipientid = p.recipientid and d.SubscriptionType = 0 and CONVERT(date, p.DateCreated) = CONVERT(date, d.DateCreated)) as Subscribed from Peo...
parismiguel
1

votes
2

answer
33

Views

Linq query order by for string

Need suggestions on how to order the strings in order in a linq query. Example of strings in db [1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.17 1.18 1.19 1.20 2.1a(i) 2.1a(ii) 2.1a(iii) 2.1a(iv) 2.1a(v) 2.1a(vi) 2.1a(vii) , ....] In order to solve the issue for a job cas...
Upriser
1

votes
2

answer
19

Views

Select two comparers in two list with same property value

I want to compare two List and select both entities with same value in the Hash property. public class Candidate : IEquatable { public string Name { get; set; } public String Hash { get; set; } } //.... //List with "CandidateA", "CandidateB", "CandidateC" values List newsCandidate = loadNewsCandida...
Onetx
1

votes
2

answer
2.4k

Views

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies

I have model contain class order in this action i create object from class order and fill data for it then serialize my object but throw exception A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Order_5247E51E921C7E989617CBA5719815085C1A2851A...
Asmaa Mohamed
1

votes
1

answer
2.7k

Views

Using navigation properties instead of LINQ Join in WebApi controller

I am using Entity Framework Code First and LINQ to Entities in a Web Api Controller. I have 3 tables that are related with the following relations/ navigation properties: (the model classes are as follows) My Reservation class: [Table("Reservations")] public class Reservation { [Key] [DatabaseGene...
Sorin Vasiliu
1

votes
2

answer
535

Views

Sorting list of strings using linq with custom sort

I am trying to sort a list of strings in an order that is pertinent to a sequence used in common revision history sequences. Some customers start with "-", or "New", or a few other specific codes, and I can use LINQ to define a custom sort order. However, after a drawing has been revised from Rev A...
AuLion
1

votes
2

answer
3.6k

Views

ThenInclude not working for an Entity Framework LINQ query [duplicate]

This question already has an answer here: Can not load related data with Include or ThenInclude or Select/Many with ONE query [duplicate] 1 answer I have a database model like this: public class Customer { public int CustomerId{ get; set; } public int OrderId { get; set; } public ICollection Orders...
Marvin Püthe
6

votes
1

answer
82

Views

Bit-Bool on a Entity Framework Scalar Function Throws 'cannot be translated' Exception

I have many working Entity Framework Scalar Function's. However, when I try to return a 'truthy' value through a scalar function I get the following exception: The specified method 'Boolean svfn_CanCloneDocument(Int32, System.String)' on the type 'ETC.Operations.DbClient.DbClient.Data.DbClientConte...
Prisoner ZERO
1

votes
1

answer
61

Views

LINQ query. Only primitive types or enumeration types are supported in this context

I want to create LINQ query checking created automatic permissions created in current month. I have list of permissions included pairs employee and company and then I want to get list of permissions created in current month for these couples. Unfortunately it return exception: "Additional informatio...
kenzolek
1

votes
1

answer
34

Views

c# linq join on multiple attributes with different names

trying to do a linq join on two attributes where the attributes have different names I am receiving. The type of one of the expressions in the join clause is incorrect type inference failed on the call to join here is the fiddle https://dotnetfiddle.net/xKg9mB here is the code using System; using...
Bryan Dellinger
0

votes
2

answer
31

Views

How to sort something in LINQ based on many dates?

Hello this is a LINQ Query but it doesn't sort properly because four different dates are involved. var EventReportRemarks = (from i in _context.pm_main_repz .Include(a => a.PM_Evt_Cat) .Include(b => b.department) .Include(c => c.employees) .Include(d => d.provncs) where i.department.DepartmentName =...
John Kamaal
0

votes
3

answer
32

Views

LINQ - Select Max of two values if count > 1

I have some LINQthat brings back some data. It consists of two properties the ChannelType and the ChannelName. Sometimes the channel type will be null and its count only 1, because the channel hasn't been set yet. The LINQ query: var channels = (from channel in db.UriData join device in db.Devices o...
The OrangeGoblin

View additional questions