.net,linq,entity-framework,include,condition , LINQ to SQL: How to create something like conditional include?

LINQ to SQL: How to create something like conditional include?


Tag: .net,linq,entity-framework,include,condition

I'd like to create a query contains User whose entities has Event with type == 1. I would also like the Event entries loaded into EventsCollection. My code would be something like .Include(u => u.EventsCollection), but this only loads all Event entries - I want to load only with type == 1.

I have simple model like this:

public class User
    public int UserId { get; set; }

    public ICollection<Event> EventsCollection { get; set; }
public class Event
    public int EventId { get; set; }
    public int UserId { get; set; }
    public int Type { get; set; }

    public User User {get; set; }

Any ideas?


Finally I've found the solution: We need fresh DataContext object with NO Event entities have been previously loaded.

Then we need to filter Events like this:

var filteredEventsCollection = db.Events
    .Where(ev => ev.Type == 1)
    .ToList(); //Materialize query here

Now we should query users like this:

var usersWithFilteredEvents = db.Users
    .Where(u => u.EventsCollection.Any(ev => ev.Type == 1))

And that is all! EF will substitute EventsCollection with data from the first query by itself.


If you are only trying to get the events where userID ==1, you can use the following. This will give you only the event you need from the Event Collection for the user.

        User u = new User()
            UserId = 60

        Event e1 = new Event() { EventId = 1, UserId = 2, Type = 3, User = u };
        Event e2 = new Event() { EventId = 2, UserId = 3, Type = 4, User = u };
        Event e3 = new Event() { EventId = 3, UserId = 4, Type = 5, User = u };
        Event e_Test = new Event() { EventId = 7, UserId = 1, Type = 5, User = u };

        u.EventsCollection = new List<Event>();


        var h = from use in u.EventsCollection where use.UserId == 1 select use;


Finding an item in a list in c#

The code below contains a foreach loop that loops through a list of string collection which contains XML. While enumerating through the collection, it reads the question and answer elements and adds them to the list collection. I need to ensure that no repeated question is added to the list...

Regex to remove `.` from a sub-string enclosed in square brackets

I have this regex in C#: \[.+?\] This regex extracts the sub-strings enclosed between square brackets. But before doing that I want to remove . inside these sub-strings. For example, the string hello,[how are yo.u?]There are [300.2] billion stars in [Milkyw.?ay]. should become hello,[how are you?]There are [3002] billion stars...

External Datepicker not working

I'm working with an external jss library that will let me use a datepicker that doesn't cut off the previous and next months dates. I'm getting an error when going through the coding. code $.fn.calendar = function (options) { var _this = this; var opts = $.extend({}, $.fn.calendar.defaults, options); var...

inconsistent timing from .net StopWatch

I have a C# & .NET application that uses a GPU (NVIDA GTX980) to do image processing. There are 4 stages and I synch the CPU to the GPU (no overlap in time) to do timing. But the numbers do not add up. Launch() will do a async launch of...

Unhandled exceptions and background workers

In our application we use several background workers which are executed using SERVICENAME__bgw.RunWorkerAsync() where SERVICENAME is one of several different background worker processes executed by different timers. We recently saw this error message that was shown after an unhandled error bubbled up to the top of the call stack: My...

check if a list contains all the element in an array using linq

I have a list of objects and I have an array of keywords. I need to check if all the elements of the array are present inside the list of objects. The user enters the data to be searched like this pain+fever+thirst+itching My code looks like: //i check if the...

Adding where clause to IEnumerable Select

I have the following line of code in my controller that selects the id's of the interests shown within a view (they are listed down the page). IEnumerable<int> interestIds = viewModel.ExistingInterests.Select(x => x.InterestId); However I want to be able to add a where clause to the select section. In ExisitingInterests...

Move windows form from a picturebox in C#

I have a windows form without any border. So i added a picture box and i want the whole form to be moved when that picture box is clicked. public const int WM_NCLBUTTONDOWN = 0xA1; public const int HT_CAPTION = 0x2; [DllImportAttribute("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg,...

Catch concurrency exception in EF6 to change message to be more user friendly

I am using EF6.1 and i would like to change the message to a more system specific message when the below exception is thrown. Store update, insert, or delete statement affected an unexpected number of rows (0) Now, my problem is i cannot seem to catch the exception? I have...

How to send Ctrl+S through SendKeys.Send() method to save a file(save as dialog)

I need to save a file which is in an External application using SendKeys.Send() method. The keys needed to be sent are Ctrl+S. I wrote the below code, but its not working: SendKeys.SendWait("^%s?"); // to get the Save As dialog Thread.Sleep(5000); SetForegroundWindow(FindWindow(null, "Save As")); Thread.Sleep(5000); SendKeys.SendWait("xyz"); // Sending FileName ...

Update list of items in c#

I would like to know if you can suggest me an efficient way to update a list of items in c#. Here is a generic example: If CurrentList is [ {Id: 154, Name: "George", Salary: 10 000} {Id: 233, Name: "Alice", Salary: 10 000}] And NewList is [ {Id: 154,...

Sort Array by contains specific char count

I have an array and I want to sort this array by its element' specific character count. var myNewArray = myArray.ToList().Sort(u => u.Name.Split(' ').Length); but this does not work at all. How can I provide the LINQ code for this problem ? myArray[0] = "word1 word2" myArray[1] = "word1" myArray[2]...

Custom drawing using System.Windows.Forms.BorderStyle?

I want to mimick drawing of default border based on value of property BorderStyle. Instead of single border around the control, my control is visualised as four adjacent custom-drawn boxes (2×2), each having standard border drawn individually. So for example, if Control.Border is set to FixedSingle value I want to...

OpenXml.WordProcessing.Justification always comes as OpenXmlUnknownElement

I'm building a table using OpenXml and setting the Justification property for every cell. It doesn't really matter where I assign this property, either in the Run element or as a TableCellProperty, when the document is open using the Productivity Tool for MS Office the Justification element always comes as...

Get List of Elements in Tree with specific Field Value

I have an Interface like this: Public Interface TreeSelectorAttributes Property selectedInTreeSelector As Boolean Property Name As String ReadOnly Property childs As IEnumerable(Of TreeSelectorAttributes) End Interface and I have a TreeView which has a List of this TreeSelectorAttributes: Public Property rootList As IEnumerable(Of TreeSelectorAttributes) now after the User chooses which elements...

Load XML to list using LINQ [duplicate]

This question already has an answer here: XDocument to List of object 1 answer I have following XML: <?xml version="1.0" encoding="utf-8"?> <start> <Current CurrentID="5"> <GeoLocations> <GeoLocation id="1" x="78492.61" y="-80973.03" z="-4403.297"/> <GeoLocation id="2" x="78323.57" y="-81994.98" z="-4385.707"/> <GeoLocation id="3" x="78250.57" y="-81994.98" z="-4385.707"/> </GeoLocations> <Vendors> <Vendor id = "1" x="123456" y="456789" z="0234324"/>...

Best approach to upgrade MVC3 web app to MVC5?

I have a web application which runs on Azure which is currently running MVC3/C#, EF6.1, .NET4.5. I would like to upgrade it to MVC5 to be: a) Current b) Get benefit of new features c) Get Performance gains. This is a part of a performance project, so hopefully there will...

orderby () containing numbers and letters

I want to order an array containing numbers and letters in an ascending order the values are stored as a string in a DB. This is the list I have 4B 1A 1 1B 2 4C 4 and want them to order like this where numbers are ascending followed by...

How to declare var datatype in public scope in c#?

I write simple query with linq to sql : var query = (from p in behzad.GAPERTitles select new { p.id, p.gaptitle }).ToArray(); up code into the c# windows application ,windows form load event,and i want use up result into the button click event in this scope: private void button1_Click(object sender,...

String Format: How to add any number of zeros before string

I'd like to have strings that have zeros before them. I use this code: string a = string.Format("{0:00}",7); The above code gives a two digits string, but what if I want a n digit string? Let's say n = 5, how can I use string.format to get something like 0004?...

How does convert.ToString(C0) behave?

I have different scenarios. I need output where the value must return comma separated values in ₹ format which it does in my system where I have the ₹ rupee symbol. Whereas in the user system C0 returns $ value with comma separated values I do not know if he...

Application is missing required files

Pic of Error: http://s23.postimg.org/7uj6qcxtn/9708083373e57a9ec91e4296e302f88e.png Cannot Download the Application. The Application is missing required Files. Contact Application Vendor For Assistance. So I'm building a windows form application using SharpDevelop 5.2 and I'm trying to make a standalone/version someone else would be able to use on another machine. In sharpdevelop (and visual...

Capturing group recursively inside non-capturing group?

So I've got the following input: 1,6-10,10000,2,10-11 And the following regex: ^\d+(?:,(\d+|\d+-\d+))*$ in the .NET Regex I want to match each of the groups between the commas but I also want the capturing groups to end up like the following: Group 1: 1 Group 2: 6-10 Group 3: 10000 Group...

Compare if the characters in a string are a subset of a second string in C#

I'm working on a game where I want to check if the characters of a string are contained in another string. Obviously a set would be my first choice but I want to account for duplicates. For example: "met".IsContainedWithin("meet"); => true "meet".IsContainedWithin("met"); => false A multi-set would be nice but...

Please help me convert this sql to LINQ

DECLARE @items table ( pfid varchar(8), timestart datetime, timeend datetime ) insert INTO @items(pfid,timestart,timeend) VALUES('123456','12:00 AM','3:00 AM') ,('987654', '2:00 AM', '4:00 PM') ,('492384', '3:00 PM', '9:00 PM') SELECT * FROM @items a INNER JOIN @items b ON a.timestart < b.timeend AND b.timestart < a.timeend AND a.pfid != b.pfid I need...

ASP.NET MVC posting list from view to controller

I have a view model in my ASP.NET MVC application: public class FiltersViewModel { public IEnumerable<SelectListItem> AvailableFilters { get; set; } // fills a drop down menu public IList<TechnologyFilter> TechnologyFilters { get; set; } public IList<ContractTypeFilter> ContractTypeFilters { get; set; } public FiltersViewModel() { this.TechnologyFilters = new List<TechnologyFilter>(); this.ContractTypeFilters =...

DialogBox with value verifications

For my application which deals with graphics, I've made a little DialogBox to set: Max; Min; Major Step (of the scale); Minor Step. Here's a screen capture: I want to validate a few things before allowing the user to click Ok: Max >= Min MaxScale >= MinScale. But it's not...

Distinct all columns in a datatable and store to another datatable with LINQ

I have a datatable with more than 10 columns and I would like to distinct all columns and then store a result to another datatable. Is there any way to distinct all columns in a datatable by using LINQ without naming all ones? I've tried as the code below but...

QUERY IN C# ,where statement

How can I write this query on c# : SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME=combobox1.text; ...

Feature-specific compatibility of a .NET 4.5 application on a system with .NET 4.0

I have a project which runs fine on 4.0, however in the interests of utilizing the new ZipFile class I have decided to target 4.5. The vast majority of my users will have 4.5+ installed, but its not impossible someone with only 4.0 may come along and try to use...

Visual Studio Assembly force-installs Target Framework

I have this Assembly targeted at .NET 3.5. The code will work on later versions as well, but I like this to work on Windows XP. I mean, .NET is backwards compatible, right? I can run apps for .NET 3.5 on Windows 8.1. However, when I run my own assembly,...

Formatting large numbers in C#

I am using Unity to make an "Incremental Game" also known as an "Idle Game" and I am trying to format large numbers. For example, when gold gets to say 1000 or more, it will display as Gold: 1k instead of Gold: 1000. using UnityEngine; using System.Collections; public class Click...

Related entity not loaded

I'm starting a new entity framework project and I'm defining relations among entities. I defined this simple entities: [Table("db_owner.Students")] public partial class User { [Key] public int Id { get; set; } [Required] [StringLength(50)] public string Name { get; set; } public int? SchoolClassId { get; set; } [ForeignKey("SchoolClassId")] public...

Why when trying to upload a video file to youtube i'm getting InvalidCredentialsException?

This is my code in form1: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.YouTube; using Google.GData.Extensions.MediaRss; using Google.YouTube; namespace YouTube_Manager { public partial class Form1 : Form { YouTubeRequestSettings settings; YouTubeRequest request; string username...

Microsoft Band and WPF

I have downloaded the sample code for Band SDK for Windows. Then I added a new WPF project and grabbed the latest SDK through Nuget (Version 1.3.10518.1). Now under packages\Microsoft.Band.1.3.10518\lib, the following folders are contained: netcore451 portable-net45+win+wpa81 portable-win81+wpa81 wpa81 Now as I need .NET 4.5 support I have referenced the...

Unconstrained type parameters casting

My situation: interface ISomeInterface { void DoSmth<T>(T other); } class Base : ISomeInterface { public virtual void DoSmth<T>(T other){ // for example do nothing } } class Derived<T2> : Base { Action<T2> MyAction {get;set;} public override void DoSmth<T>(T other){ if(typeof(T2).IsAssignableFrom(typeof(T))) MyAction((T2) other); } } This gives me an error: Cannot...

How does the Take() method work in LINQ

I have a question regarding LINQ's Take() Method. I have a somewhat large table I'm querying in my web app, and I only want to return say N number of rows from the table. I've read through the MSDN documentation, but I can't see where it states if Take() first...

sqlite query slow, how to optimize (using linq to entities)

I have used MS SQL server a few times and have yet to run into a speed issue when querying, using linq to entities. This time, I am using sqlite, as to ship the entire database with the application. I have a winforms app that contains 4 search fields. My...

Is Serialization the same as GetBytes?

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes. Found this on google. I use .Net to send packets using a socket connection. I use Encoding.Default.GetBytes(). Serialization is confusing, what is the difference of it to GetBytes?...

How can I determine if an object of anonymous type is empty?

I am sure the answer to this is quite simple but I am trying to write an if statement (C# 5.0) to determine whether or not an anonymous type is empty or not. Here is a simplified version of my code: public void DoSomething(object attributes) { // This is the...

Does MongoDB successful insert guarantee populated ID's?

We are using the MongoDB C# driver to insert a collection of records using InsertManyAsync. We currently have code that iterates the entire collection after InsertManyAsync returns, confirming that the ID's are populated. I would expect that the driver takes care of this already, but I have not found documentation...

How do I convert this tSQL statement to LINQ using group by in a sub query

I have the following MSSQL query I am trying to convert to LINQ. I am using entity framework with the following syntax to get at the data. var rv = (from i in DC.TableA select i).ToList(); This is the sql I want to write a C# LINQ query for but...

Error when building an XDocument

Using the following example xml containing one duplicate: <Persons> <Person> <PersonID>7506</PersonID> <Forename>K</Forename> <Surname>Seddon</Surname> <ChosenName /> <MiddleName /> <LegalSurname /> <Gender>Male</Gender> </Person> <Person> <PersonID>6914</PersonID> <Forename>Clark</Forename> <Surname>Kent</Surname> <ChosenName>Clark</ChosenName> <MiddleName />...

Linq update with specific select of column being null

I wanted to select few columns from SQl and then update that table. I used var xyz_repl= from mfrepl in xyz_repl_alias where (mfrepl.RPT_ID == sched_data.NOTIF_RPT_ID) && (mfrepl.NOTIF_ID == "" || mfrepl.NOTIF_ID == null) select mfrepl; This did my job but then it does not work if any column is NULL.Then...

Can't access any of Linq methods

I'm writing a simple ApiController for getting product stocks, but I'm having a strange issue. I get the data from a method that returns a System.Linq.IQueryable (In a library), but I can't apply any of the Linq methods, like Count or ToList(). The import directive is present and doesn't report...

Updating entity framework model using Linq

I have a problem with updating data in an entity framework model. I have a few tables in the model (Users, UserActivity and Orders). I have added associations between the tables, one between Users and UserActivity and one between Users and Orders. The associations are through the column UserID. These...

how can I add a column to IQueryable object and modify its values

var packs = from r in new XPQuery<Roll>(session) select new { Number = r.number Selection = new bool() }; gcPack.DataSource = packs; I want to add another column to my grid control with: Selection = new bool(). It will be added to the grid but I can't change its...

XElement.Value is stripping XML tags from content

I have the following XML: <Message> <Identification>c387e36a-0d79-405a-745c-7fc3e1aa8160</Identification> <SerializedContent> {"Identification":"81d090ca-b913-4f15-854d-059055cc49ff","LogType":0,"LogContent":"{\"EntitiesChanges\":\" <audit> <username>acfc</username> <date>2015-06-04T15:15:34.7979485-03:00</date> <entities> <entity> <properties> <property> <name>DepId</name> <current>2</current> </property>...