Questions tagged [linq-to-entities]

1

votes
1

answer
990

Views

Getting entities of a certain type using entity frameworks return error - LINQ to Entities does not recognize the method 'System.Type GetType()'

I am trying to filter out entities of a certain type. I am using Entity Framework, and I have a parent entity, and various children that inherit from the parent entity. I am trying to filter out one of these children. For example, I have the following structure: Address : Entity PostCode : Address...
Karan
1

votes
4

answer
250

Views

Convert simple Left Outer Join and group by SQL statement into Linq

2 tables: User and Alarm Table:User UserID(int), FullName(varchar) Table:Alarm AssignedTo(int), Resolved(bool) Query: SELECT u.Fullname, COUNT(resolved) as Assigned, SUM(CONVERT(int,Resolved)) as Resolved, COUNT(resolved) - SUM(CONVERT(int,Resolved)) as Unresolved FROM Alarm i LEFT OUTER JOIN User...
Wizardre
1

votes
1

answer
431

Views

LINQ Conditional Composite key in INNER JOIN

Let's say I have an Order and OrderDetails collections. How can I write following sql in LINQ (query or fluent syntax)? select top 1 OD.ProductId from Order O inner join OrderDetail OD on OD.OrderID = 1 and OD.OrderId = O.OrderId and ((OD.OrderDate = O.OrderDate) or (OD.OrderDate is null)) where O.C...
Syed Danish
1

votes
2

answer
97

Views

not able to select in Group by Entity Framework

I have this SQL query which I am trying to translate into Linq SELECT DATEPART(yyyy, ce.DueDate) AS year, DATEPART(mm, ce.DueDate) AS Month, COUNT(CASE WHEN rt.Code = 'Pass' THEN 1 ELSE NULL END) AS NumPass, COUNT(CASE WHEN rt.Code = 'Fail' THEN 1 ELSE NULL END) AS NumFail FROM ControlEvent ce INNE...
Ahsan
1

votes
2

answer
994

Views

Filter by nullable datetime field using Linq

I'm trying to filter all rows in an SQL table that have a specific date. It works if the column is not nullable, but fails if it is. This works for not nullable datetime fields: ent.MyTable.Where(e => e.MyDate.Day == 12); Obviously this works not for nullable datetime fields. After doing some search...
user1000742
1

votes
1

answer
1.2k

Views

Entity Framework Code First override onModelCreating() for TPT Inheritance Screwing Up Identity User and Role Models [duplicate]

This question already has an answer here: The entity type 'Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin' requires a key to be defined 1 answer I'm having problems extending the Fluent API to my inheritance classes. I have taken the TPT (table per type) method and each type of the in...
dev8989
1

votes
2

answer
260

Views

Using multiple LINQ “Include” to get 2nd depth data

I have the following model (simplified) public partial class Fault { public int FaultID { get; set; } ... public virtual ICollection FaultComments { get; set; } public virtual User FaultCreatorUser { get; set; } } public partial class FaultComment { public int CommentID { get; set; } public int Faul...
Mortalus
1

votes
2

answer
1.2k

Views

Populate a list property from delimited string

This is kind of a simple application but I'm a bit new to ASP.NET MVC so I'm having a bit of trouble wrapping my head around how to accomplish this because the What I have are two classes: public class BugAssignment { public int BugAssignmentID { get; set; } public int BugNumber { get; set; } public...
Josh
1

votes
1

answer
2.3k

Views

Efficient way to get previous n day by date data from LINQ/EF

I have a Sales tables that holds all order details. It has columns ID, SaleDate, Price. Through Entity Framework v4, what is the efficient way to get day by day total sales for previous 30 days? public static List GetTotalsByDate() { List totals = new List(); ChartTotal totalForDay = null; DateTime...
Null Head
1

votes
3

answer
110

Views

LinqToSql query loading unwanted data into memory

I am simulating a join on a linked server through linq to sql. My question is, it appears that linqtosql is bringing all the rows for y.Xstatuses into memory and then doing the join. If this is true how do i keep all the memory on sql server(and still do a cross datacontext join operation), if this...
gh9
1

votes
2

answer
41

Views

User is duplicated when calling Reply

I'm trying to make a simple forum using MVC and I can't figure out why the user that is posting the reply is getting duplicated. Here is the Reply Action: [HttpPost] public ActionResult Reply(string Title, string Content,int ReplyTo) { Post masterPost = db.Posts.FirstOrDefault(p => p.PostID == Reply...
Imri Barr
1

votes
2

answer
79

Views

Query to include non-protected resources only

I am using Entity Framework to retrieve data from my database. You can see the database model here: I'm attempting to build a repeater where I show Resource Categories only if there is a resource where IsProtected == false. Then an nested repeater showing the Resource itself. Here is an abbreviated...
Jon Harding
1

votes
2

answer
65

Views

How to select mutiple rows from Entity using Linq

I want write a LINQ query equivalent to select * from Users where Username in ('[email protected]', '[email protected]') Is it possible to write this in LINQ?
Vivek Patel
1

votes
2

answer
3.8k

Views

Convert SQL to LINQ: select the result into model

I'm not familiar with LINQ, can any one help me out? Thanks in advance. My model: public class OrderOverViewModel { public int Quantity { get; set; } public String ACCN { get; set; } public DateTime OrderDate { get; set; } } And this is the SQL: SELECT COUNT(*) AS HowMany, DATEADD(dd, 0, DATEDIFF(d...
Wayou
1

votes
3

answer
412

Views

Avoiding Stack Overflow Exception

I am stuck with a stack overflow exception in this section of code, it is obviously occurring because the Customer object calls a list of CustomerBackgroundLevel objects, each one of which creates a new customer object. I am trying to find a way around the issue, any help would be appreciated.. Cust...
user1948635
1

votes
3

answer
368

Views

Why do I have do assign subquery to a variable outside of my main query

In the GetTransfers() method below I have to assign the result of GetAllocations() to a variable outside of my main query otherwise the query fails. Why do I have to do that? Is there a better way? When the query fails I get this error: {System.NotSupportedException: LINQ to Entities does not re...
Sam
1

votes
2

answer
216

Views

Converting LINQ Extension method to work with L2E

I am working on a search page where users are able to use wildcards * in their search criteria. The wildcard can be placed at the beginning, or end of a string. Since there are several fields I need this to be applied to, I figured an extension method would be the best way. The code I came up with c...
Jeff
1

votes
5

answer
594

Views

How to Copy Common properties List<x> to List<y>

how to copy list to another list class x and class y both have several common properties want to copy common properties to another list ,suppose x to y Have two list one to copy one list content to another, I use bellow syntax to copy list to list items. List list1 = new List(); List list2 = new L...
shamim
1

votes
1

answer
878

Views

Entity Framework .Any does not generate expected SQL WHERE clause

Entity Framework and Linq-To-Entities are really giving me some headaches. I have a fairly simple query: var result = feed.FeedItems.Any(ei => ei.ServerId == "12345"); feed is a single EF entity I selected earlier in a separate query from the same context. But the generated SQL just throws away the...
Bernhard Koenig
1

votes
1

answer
212

Views

Create a query using LINQ to entities with 1:N relation

I know it's not something unusual to make such kind of queries but I think I get lost so I seek help. I have to tables with relation 1:N and to make it more clear I'll post a print screen from the management studio : I am working on a asp.net mvc 3 project and I need to make a view where all Documen...
Leron
1

votes
3

answer
6.7k

Views

How to convert SqlDataReader to LINQ way?

I wonder how to convert SqlDataReader to LINQ way? Here is my SqlDataReader code. string strConn = "server=xxx.com;database=mydb;User ID=test;Password=test;Trusted_Connection=true;"; SqlConnection myConn = new SqlConnection(strConn); myConn.Open(); string strSQL = "select period from timetable_view...
user2401077
1

votes
3

answer
221

Views

C# generic method type constraint to several classes

I have something like this: public List GetPageRows(Expression predicate, List sortOrder, int pageSize, int pageNo) where T : Type1, Type2, Type3 { var filteredQueryable = GetRowsAndFilter(predicate); var orderedQueryable = GetOrderedQueryable(sortOrder, filteredQueryable); var pagedQueryable = orde...
pinkfloydhomer
1

votes
2

answer
586

Views

Get only some properties from an entity using Repository pattern and LINQ2Entities

I know it's pretty standard stuff but right know the solution escapes me. I have entity Documents. In my service I can call DocumentsRepository.All() and then use only what I need but I don't want to carry all the unneeded data. I guess I have to use anonymous object to achieve this, but the exact...
Leron
1

votes
3

answer
79

Views

How do I convert the following functions/expressions from SQL to LINQ to Entities?

Dateadd(minute, TS.duration, TS.datesched) WHERE... TS.Duration = int. TS.datesched = datetime. RTRIM(ISNULL(TC.CityLocation, '') + ' ' + ISNULL(TC.StateLocation, '') WHERE... TC.CityLocation = varchar(50) TC.StateLocation = varchar(10) CASE WHEN country = market OR country = 'USA' THEN market E...
Rj.
1

votes
2

answer
670

Views

Compare elements of an object resides in two list - one on one using LINQ

I'm trying to find out is there any better way other than Enumerable.Range in WHERE clause to compare object's elements one on one. It could be a parallel since We're comparing one on one here. For example: House.Windows[0].color != House1.Windows[0].color and then movenext to House.Windows[1].colo...
1

votes
6

answer
272

Views

Return List<User> using Linq to Entities

I'm developing a WCF Rest service that connect to a database using Entity Framework 4.4. I have this method: public List GetAllUsers() { using (var context = new AdnLineContext()) { var users = from u in context.Users select u; } } And I don't know how to return a List with all Users retrieved from...
VansFannel
1

votes
2

answer
1.7k

Views

Does OrderBy followed by Skip and Take compile into query or run in memory?

Say I have a query like this one: var result=collection.OrderBy(orderingFunction).Skip(start).Take(length); Will the whole query run on SQL server and return the result, or will it return the whole ordered table and then run Skip and Take in memory? I am concerned because I noticed that OrderBy retu...
m0s
1

votes
2

answer
2.9k

Views

How to integrate a Linq to Entity query that queries multiple entities in a repository and send data to View?

I'm learning MVC, the repository pattern and EF and I need some advice as to how best to integrate a method which contains a query that queries multiple entities into the repository. At the moment, I have created a repository class which implements an interface and uses an instance of DbContext to...
Colin Roe
1

votes
1

answer
3.4k

Views

linq to entities contains does not work

I am new to linq to entities and I have a problems in using the contain method. Here is the sample table in my DB. DataTable UserTable = new DataTable(); UserTable .Columns.Add("ID", typeof(int)); UserTable .Columns.Add("Name", typeof(string)); UserTable .Rows.Add(1,"Tom"); UserTable .Rows.Add(2,"To...
austinc
1

votes
2

answer
4.7k

Views

How to use Convert.Int32() method in LINQ to Entities Join?

I have a problem with LINQ to Entities query, I am joining four tables but there two tables that don't have the same datatype for the join column below is the query. var qry = (from i in dc.INTERNETDATAs join c in dc.COVERS on Convert.ToInt32(i.COVERTYPE) equals c.COV_TYPE join b in dc.BENEFITS on c...
Mitz
1

votes
2

answer
235

Views

Entity Framework - Why does this Linq query generate multiple round trips?

I have 3 tables: Product, Category, and ProductCategory, where ProductCategory is the join table for a many-to-many relationship between Product and Category. The following Linq query (which is an extension method in the Category class) results in a round-trip for each ProductCategory record withi...
Keith
1

votes
2

answer
3.2k

Views

Unable to cast object of type 'Grouping[System.String,MyProject.ViewModels.MyViewModel+MyClassData]' to type 'MyClassData'

I am having an issue with grouping in my ASP.NET MVC4 (Razor View Engine) VS 2012 project. I am using Entity Framework. My code is below: Thanks for any help. I am getting the error Unable to cast object of type 'Grouping[System.String,MyProject.ViewModels.MyViewModel+MyClassData]' to type 'MyCla...
KeyboardFriendly
1

votes
2

answer
727

Views

Unknown Select(?) of System Data Entity DbSet

Is something like this possible? I am getting the below error. db.SomeTable.Add(new SomeTable() { GuidId = Guid.NewGuid(), Name = db.AnotherTable.Select(x => x.Name.Where(x.Id == localVariable.Id)) } ); db.SaveChanges(); Unknown Select(?) of System Data Entity DbSet
user1307149
1

votes
2

answer
1.1k

Views

Dynamically Building Linq to Entities Lambda Expression with Concatenated Properties

I recently ran into the requirement to implement server side filtering for a Kendo UI grid control. Since the comparison operator(s) in the linq to entities lambda expressions wouldn't be known at compile time, it was necessary to build the expressions dynamically. I've never had the need to do this...
grin0048
1

votes
2

answer
887

Views

Excluding large List<int> from LINQ to Entities query

I have a List containing a high number of items - up to 10,000. I am looking for the most efficient way to exclude these from an IQueryable/List. Due to the complexity of the process involved in obtaining this list of Ids, it isn't possible to do this within a query. The example below has an extreme...
Nick
1

votes
2

answer
742

Views

linq with null condition

How can the foll. sql be written in Linq. I am using LinqToEntities,C#. @companyID & @branchID are the parameters select * from tblEmp e where e.deleted = 0 and (e.companyId = @companyID OR e.companyid is null) and (e.branchId = @branchID OR e.branchid is null) For now, there is a stored procedure f...
Ruby
1

votes
2

answer
49

Views

How can I make this C# class and method static?

I am a new ASP.NET developer and I am trying to learn Linq-To-Entities. I am trying to create a static class called Items in my Data Access Layer. This class has a method to retrieve all the records in Items Entity. And then, I will use it for binding the GridView to it. The problem is that I got th...
user3107976
1

votes
2

answer
421

Views

Get string range in Lambda Expression [duplicate]

This question already has an answer here: Compare DateTime as a string into a LINQ to Entities doesn't recognize DateTime.parse(string) 4 answers I want to do a query with Lambda expression to get values where result set is between a certain range. The value type string in the database and is used...
Gericke
1

votes
2

answer
193

Views

Linq-to-EF with nullable decimals & math functions

I have a Clinics table in SQL2008 which has nullable decimal Latitude and Longitude columns (nullable as I don't have coords for all clinics). I'm using Linq-to-EF and would like to calculate / sort the records by the distance from a given point. For simplicity's sake, let's say the distance calcula...
Sean
1

votes
1

answer
33

Views

Looking for a list of items in a query

I am passing a string list of studentKeys to my LINQ to Entities query. So I want to return those data that are in that coming list. public IQueryable GetStudentsFromKeys(List studentKeys) { var result = from a in this.Context.Students where // ? return result.ToList(); } But How should I actually w...

View additional questions