Linq Persistence framework?

I'm trying to decide on the best strategy for accessing the database. I understand that this is a generic question and there's no a single good answer, but I will provide some guidelines on what I'm looking for. The last few years we have been using our own persistence framework, that although limited has served as well. However it needs some major improvements and I'm wondering if I should go that way or use one of the existing frameworks. The criteria that I'm looking for, in order of importan

How do I use Linq to obtain a unique list of properties from a list of objects?

I'm trying to use Linq to return a list of ids given a list of objects where the id is a property. I'd like to be able to do this without looping through each object and pulling out the unique ids that I find. I have a list of objects of type MyClass and one of the properties of this class is an ID. public class MyClass { public int ID { get; set; } } What I want to do is write a Linq query to return me a list of those Ids How do I do that given an IList<MyClass> such that it return

Linq to Nibernate design

I thought that the purpose of using Linq2Nibernate was to return IQueryable and build up an expression tree. I am not sure if this is correct or not. Why would anyone use Linq2Nibernate if they are not going to return IQueryable? What else would it be used for? I would love some more input on this topic Linq For Nhibernate

Linq Can't get a collection in a entity class

Suppose I have following tables with the right relationships built: Employee(empID, ...) Address(AddresID, ...) EmployeeAddress(EmpID, AddressID, ...) Then modified the generated code for GetEmployee by .NET RIA Services like: public IQueryable<Employee> GetEmployee() { var Employee = this.Context.Employee.Include("EmployeeAddress").Include("Address"); return Employee; } Attribute [Include] has been added for EmployeeAddress in Employee and Address in EmployeeAddress. W

SharePoint, List.Items and List.GetItems(Query) and Linq

Following on from suggestions, I am trying to use List.GetItems(Query) to retrieve my initial data subset rather than the entire list contents via List.Items. However, whereas List.Items.Cast() results in a usable IEnumerable for Linq, List.GetItems(Query).Cast() does not. Working Code: IEnumerable<SPListItem> results = SPContext.Current.Web.Lists[ListName].Items.Cast<SPListItem>().Where(item => item["Date"] != null).Where(item => DateTime.Parse(item["Date"].ToString()) >

Help me convert this SQL query to LINQ

I'm trying to convert this SQL query to LINQ: SELECT Items.p_Name Product, DiamondCategory.dc_Name Category, Diamond.d_Weight Weight FROM DiamondCategory INNER JOIN Diamond ON DiamondCategory.dc_Id = Diamond.dc_Id INNER JOIN Items ON Diamond.p_Id = Items.p_Id where Items.p_Id = 1 Union gives no results: var qry = (from d in myDatabaseDataSet.Diamond select d.d_Weight).Union (from c in myDatabaseDataSet.Items select c.p_Name).Union (from e in myDatabaseDataSet.DiamondCateg

What is the return type for a anonymous linq query select? What is the best way to send this data back?

This is a basic question. I have the basic SL4/RIA project set up and I want to create a new method in the domain service and return some data from it. I am unsure the proper easiest way to do this.. Should I wrap it up in a ToList()? I am unclear how to handle this anonymous type that was create.. what is the easiest way to return this data? public IQueryable<ApplicationLog> GetApplicationLogsGrouped() { var x = from c in ObjectContext.ApplicationLogs let dt

Correct MultiChoice Values in LINQ to SharePoint Query

I am using a LINQ to SharePoint query to return items from a SharePoint list. var myOpenTasksQuery = from myTasks in tasks where myTasks.TaskStatus != TaskStatus.Completed select myTasks However, the list I am querying, an OOTB Tasks list, there are a number of multi-choice fields (Status, Priority), which are translated into enumerations. In my query results, a task item status is returned as "_2Normal", and not as "(2) Normal" as I would expect

Linq Query Help

I have the following Linq query: from etamodule in ETAModule join eta in ETA on etamodule.ExpID equals eta.ExpID where etamodule.SubID== "101106261013" select new { etamodule } ETAModule has a 1:1 relationship to ETA. However, there is not a FK in the database that enforces this (unfortunately). The way my query is constructed works fine, but I would like to include the ETA entity for each ETAModule entity, as a property of the ETAModule entity. Of course, this would be much easier if a FK e

Linq Generic Repository

I'm working on incorporating some common repository infrastructure into some applications that wrap EF, L2SQL and WCF Data Services (though the underlying Data Access implementations should be arbitrary). I've done some reading on the matter but can't seem to find an example that really satisfies. I started with: public interface IRepository : IDisposable { IQueryable<T> Query<T>(); void Attach(object entity); void ForDeletion(object entity); void SaveChanges(); }

Is LINQ faster or just more convenient?

Which of theses scenarios would be faster? Scenario 1: foreach (var file in directory.GetFiles()) { if (file.Extension.ToLower() != ".txt" && file.Extension.ToLower() != ".bin") continue; // Do something cool. } Scenario 2: var files = from file in directory.GetFiles() where file.Extension.ToLower() == ".txt" || file.Extension.ToLower() == ".bin" select file; foreach (var file in files) { // Do som

Dynamically Sorting with LINQ

I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate. I have a string that reflects the name of the property the collection should be sorted by. In addition, I have a sorting direction. How do I dynamically apply this sorting information to my collection? Please note that sorting could be multi-layer, so for instance I could sort by LastName, and then by FirstName. Currently, I'm trying the following without any luck: var

Returning LINQ to Entities Query Result as JSON string

I'm attempting to construct a web service that allows for RESTful requests to return LINQ to Entities data as JSON string data. I have no problem executing a call to the database that returns one specific object: public Product GetTicket(string s) { int id = Convert.ToInt32(s); MWAEntities context = new MWAEntities(); var ticketEntity = (from p in context.HD_TicketCurrentStatus where p.Ticket_ID == id

Refactor to filtering lists using LINQ

I use several lists of similar objects. Anyone object has a List property. Basically, I need compare several lists. I would have thought that LINQ would be an ideal way of doing this but after trying joins, extension methods, using yields, etc. I'm still having trouble. any suggestions for refactor my code to using LINQ ? Update: I'm refactor ContieneServidor (ContainsServer translate) method private static bool ContieneServidorRefactoring(List<GrupoServidorDto> datosGruposServidores,

Linq Iterate data in anonymous variable

I have a DataTable containing some data, and I am going to fetch some data from it using Linq to datatable. The query looks like this: var requiredData=dt.AsEnumerable() .Where(row => row.Field<byte>("id") == 1) .Select(x=> { id = x.Field<int>("id"), YYYYY = x.Field<string>("ColumnName2"), ZZZZZ = x.Field<string>("ColumnName3") } ); Now, Please how do I iterate-through "requiredData"?

LINQ query for social network: how to perform a friends feed?

I have a social networking website and I'm getting some difficulties to filter who can see the updates users post. As in Facebook, I see all posts from my friends, even if I didn't post anything. I have these tables: DiaryPosts table: -------------------------------------- | ID | UserID | Content | UpdateTime | -------------------------------------- Friends table: -------------------------- | ID | UserID | FriendID | -------------------------- Followers table: --------------------------

Linq How can i made a pivot for this

I have linq that return my data in this format Servicio2 | Indicador | Accion1 Servicio2 | Indicador | Accion2 Servicio1 | Indicador1 | Accion1 Servicio1 | Indicador1 | Accion2 Is there a way to transform the output to this Servicio2 | Indicador | Accion1 , Accion2 Servicio1 | Indicador1 | Accion`, Accion2 Based on this linq from A in db.IndicadorServicioAccion .Include("Accion") .Include("IndicadorServicio")

Ambiguous invocation caused by picking up two versions of System.Linq

I have the following code, which shows a squiggly red line under the lambda expression after .Any( because of an "ambiguous invocation" between System.Linq versions 3.5 and 4.0 - how do I force it to use a particular version? It compiles and runs fine. string[] allowedExtensions = { "PNG", "JPG", "JPEG", "GIF" }; string fileExtension = (Path.GetExtension(postedFile.FileName) ?? "NULL").ToUpper().TrimStart(new[] { '.' }); if (this.MediaService.FileAllowed(postedFile) && allowedExt

Linq query Left Join condition

I'm trying to recreate the following sql query using Linq syntax, for some reason it is not working, please let me know what am I doing wrong here My sql query: select cf.VisitConfigId, cf.VisitName, sv.VisitDate from SubjectVisitConfig cf left join SubjectVisit sv on cf.VisitConfigId = sv.VisitConfigId My Linq query: var q = from cf in ctms.SubjectVisitConfigs join sv in ctms.SubjectVisits on cf.VisitConfigId equals sv.VisitConfigId into JoinedVisits from sv in

LINQ Lamba Select all from table where field contains all elements in list

I need a Linq statement that will select all from a table where a field contains all elements in a list<String> while searching other fields for the entire string regardless of words. It's basically just a inclusive word search on a field where all words need to be in the record and string search on other fields. Ie I have a lookup screen that allows the user to search AccountID or Detail for the entire search string, or search clientID for words inclusive words, I'll expand this to the de

Linq left join without explicit relationship in nhibernate

I have these two simplified entities: public class Measurement : Entity { public virtual float DisplayValue { get; set; } private DateTime _timeStamp; public virtual DateTime TimeStamp { get { return _timeStamp; } set { _timeStamp = value.ToUniversalTime(); } } } public class TimeStamp : Entity { public virtual DateTime TimeStampEntry { get; set; } } And I am using this (my)sql code to determine missing values over a range: SET time_zone='+0:00'; se

How to AND predicates in the WHERE clause in a LINQ to RavenDB query

I have the following model: public class Clip { public Guid ClipId { get; set; } public IList<StateChange> StateChanges { get; set; } } public class StateChange { public string OldState { get; set; } public string NewState { get; set; } public DateTime ChangedAt { get; set; } } And this is how a query raven: var now = DateTime.UtcNow; var since = now.AddSeconds(60); string state = "some state of interest"; using (var session = docStore.OpenSession()) {

Linq with where clause in many-to-many EF Code First object

In an MVC4 project, using code first, I have the following: public class Course { public string CourseId { get; set; } public string Name { get; set; } public bool IsActive { get; set; } public virtual Categories ICollection<Category> { get; set; } public Course() { Categories = new HashSet<Category>(); } } public class Category { public string CategoryId { get; set; } public string Name { get; set; } public virtual Courses ICollection<Cou

Linq Add rows to a DataTable from a query expression result

I am trying to dynamically add rows to a datatable from a query expression result. However, I am getting the below exception : "Cannot cast DBNull.Value to type 'System.Int16'. Please use a nullable type." This is my code: foreach (var linqItem in linqResult) resultDT.Rows.Add(linqItem.GetType().GetProperties().Select(p => p.GetValue(linqItem, null)).ToArray()); Please help me figure out figure out this issue. Additional Code: var linqResult = from misDTRow in misUs

LINQ NHibernate, latest related entity

How do I convert this in a LINQ for NHibernate statement or queryover? Is it possible at all? Seems like a standard thing (latest related object must meet some criteria). select item, tag from MyItem item join item.Tags tag where tag.Id = ( select max(tag2.Id) from MyItem item2 join item2.Tags tag2 where item2.Id = item.Id group by item2.Id ) Best regards,

insert data into two different tables using Linq

I am using ASP .net framsework 4.5 MVC4 I have two different tables as follows public class Product { public int ProductID { get; set; } public string Name { get; set; } public string Description { get; set; } public DateTime CreateTime { get; set; } public DateTime LastUpdateTime { get; set; } public virtual List<ProductVariants> ProductVariants { get; set; } } public class ProductVariants { public int ProductVariantsID { get; set; } public int Produ

Dynamic linq/lambda expression from query

I have data query and want to create dynamic linq/lambda expression which i can run on entity collection. Not sure how to do this using Expression builder. Please provide some examples if possible. For e.g I have query Select,person.surname from person where 'Joe' and i have entity collection of all persons. But dont want to fire a query instead want to convert this query in to lambda and run on persons collection. This to avoid server calls. linq/lambda express

Nested LINQ query

I'm trying to perform a nested linq query. public class Sic { public int Id { get; set; } public string Code { get; set; } } public class Message { public List<Sic> Sics { get; set; } public int Id { get; set; } } List<Message> msgList = new List<Message>(); Message m1 = new Message { Id = 0, Sics = new List<Sic>() { new Sic() {Id = 0, Code = "A2A"},

use linq to Convert List<List<T>> to List<T> removing duplicate

I have a class T defined as follow: public Class T { public int myKey{get;set;} public datetime other {get;set;} } How do I convert a List<List<T>> to List<T>, excluding the duplicates, using Linq? Without Linq, this could be easily done by this snippet: List<T> r = new List<T>(); foreach (var i in t) { foreach (var j in i) { if (!r.Select(x=>x.myKey).ToList().contains(j.myKey)) { r.Add(new T(){myKey= j.myKey, other=j.other});

Entity Framework LINQ - dynamically select properties

Is it possible to create a dynamic selector like the below one in a simple way, and how? Func<Company, string> companyName = x.CompanyName; Func<Company, int> companyId = x.CompanyId; var result = datacontext.Select(x => new { CompanyName = companyName, CompanyId = companyId }); The above code throws exception: "Unable to create a constant value of type 'System.Func`2... ...Only primitive types or enumeration types ar

Linq VS2012 DBML Changing Connection String

I have a solution which contains multiple projects, such as a class library, websites, services, etc. Projects such as the class library and service have a dbml connection to the same database. This means that the projects have connection strings such as: MySolution.ClassLibrary.DatabaseA MySolution.ClassLibrary.DatabaseB MySolution.ClassLibrary.DatabaseC MySolution.Service.DatabaseA MySolution.Service.DatabaseD This is a bit messy as I'm duplicating the connection strings. For integration p

Running a LINQ query for multiple years

I have the below query that I need to run for multiple years say between 2010 and 2016. FirstValidYear in the below query is an integer year value I get from a different query. Whatever value that is say if its 2010, then I am looking for a way to run the query for years 2010 through 2016 (between FirstValidYear and FirstValidYear +6) var ValidationList = ( join t1 in table1 join t2 in table2 on t1.colID equals t2.ID where t1F

MSCRM 2011 EntitCollection and LINQ empty resultset

I have an EntityCollection ec in C# which has been populated with all Accounts. Now I want another List or EntityCollection from ec which has all the accounts with status active. I am using Linq for the same. But both form of LINQ returns a an empty result while ec has 354 number of records var activeCRMEC = (from cl in ec.Entities where cl.Attributes["statecode"].ToString()=="0" select cl); OR var activeCRMEC = ec.Entities.Where(x => x.Attributes["statec

Querying the min element using LINQ inside Tasks

I'm kinda new to LINQ and so I struggle with the predicates and hence I need your help. I have a parent task which returns me a collection ex: a list, List<CSample>. The object can basically be represented as below: public class CSample { public double Distance { get; set; } public double XPosition { get; set; } public double Error { get; set; } } Coming to my parent task, I have to continue with the processing of the CSample collection items once all my child t

Create ext methd accepting separated values and filter on, separated string while creating expression and convert it to lambda expr for linq where

Extension method: public static bool Contains3(this IQueryable<string> tobechecked, IEnumerable<string> value) { List<string> re = tobechecked.ToString().Split(',').ToList(); if (re.All(a => value.Contains(a))) return true; else return false; } private static MethodInfo ContainsNew = typeof(ExpressionBuilder).GetMethod("Contains3", BindingFlags.Public | BindingFlags.Static); ParameterExpression param = Expression.Parameter(typeof(T), "t"); M

Linq Use ExecuteQuery<T>() on an SQLiteCommand

In LINQPad 4, when I try to run the following code: void Main() { using (var conn = new SQLiteConnection(@"C:\linqToSqlite")) { var query = new SQLiteCommand(conn); query.CommandText = "SELECT * FROM MyTable"; var result = query.ExecuteQuery<MyTable>(); } } I receive the following error: 'System.Data.SQLite.SQLiteCommand' does not contain a definition for 'ExecuteQuery' and no extension method 'ExecuteQuery' accepting a first argument of type 'Sy

How to convert string to nullable int LINQ

I saw a lot of questions like this but seems I cant find anything to relate one to another and find solution for mine. I am using MVC 4 application where I have a dropdownlist with some values inside. I am using viewbag to populate it. ViewBag.Roles = new SelectList(db.Roles, "RoleId", "RoleName"); In the view my dropdown looks like this. @Html.DropDownList("selectedRole", ViewBag.Roles as SelectList, String.Empty) The string selectedRole is getting the RoleId value from the view. After

LINQ Logic, Navigating to the ApplicationUser Identity table, roles and a business object called project

I'm trying to grab a list of ApplicationUsers that have role type of 'Project_Manager' and that are not assigned to a projectId I pass in. I've tried to write this several different ways but the outcome is not what I'd expect. Any suggestions with my logic? var pmNotAssigned = (from p in db.Project from u in p.Users where p.ProjectId != projectId && u.Roles.Any(r => r.RoleId == db.Roles.FirstOrDefault(rr => rr.Name == "Project_Manager").Id) select u

Linq Aggregate with OrderBy and ThenBy

I have a list which elements follows a sequence. I want use aggregate with OrderBy and ThenBy List<string> list = new List<string> {"codCustomer", "customerName", "address1", "address2"}; list = list .OrderBy(o => o.codCustomer) .ThenBy(o => o.customerName) .ThenBy(o => o.address1) .ThenBy(o => o.addres2) This list contain many elements and I want use aggregate with OrderBy and ThenBy, but I don't know how do it. The matter is that this list is passed

Linq Dealing with NULL date ( 0001-01-01 10:30:00 AM)

I have a SharePoint workflow that is calling a WebService to update SQL table. One of the items to update is a completion date. If I pass it as a datetime to the WCF service, I get a BADRequest. I managed to get the update to work if I send the date as string, and then use the Convert.ToDatetime during my LINQ update functions. The issue I have is that if the date is empty, I get the classic 0001-01-01 10:30:00 AM date value. I have tried the following command to use NULL value. jcent.JobD

linq join query for getting one record from 2nd table

I Have two table table 1 ID name 1 a 2 b 3 c table 2 id date 1 4/4/2016 1 4/5/2016 2 6/6/2016 3 7/7/2016 3 7/8/2016 expected result id name date 1 a 4/4/2016 2 b 6/6/2016 3 c 7/7/2016 Here I tried some query its returning me the full records but I need only the smaller date from the table 2 can any one let me know how can I get the query for the same. from p in table1 join n in table2 on p.Id equals n.Id sele

LINQ query to match values in inner collection

Looking for a LINQ implementation to handle following use case. Pesudo definitions of object: class Product{ int Id; string Name; IList<ProductAttribute> ProductAttributes; } class ProductAttribute{ int Id; string Name; string Value; } I have collection of products that look something like: [ {"Name":"Red Large Shirt", "ProductAttributes": [{"Name": "Color", Value:"Red"},{"Name":"Size", "Value":"Large"}, {"Name":"Type", "Value":"Shirt"}]}, {"Name":"Red Small Shirt", "ProductAttribute

LINQ GroupBy two object properties and SUM, AVG, or Ignore others using Lambda

I have List of objects that I would like to group together using LINQ Lambda syntax. public class Candy { public string Id {get; set;} public string Name {get; set;} public string Distributor {get; set;} public int Quantity {get; set;} public decimal UnitPrice {get; set;} } A sample collection List<Candy> might look like the following: { Id = "AF001", Name = "Atomic Fireball", Distributor = "Wonka Candy", Quantity = 100, UnitPrice = 1 } { Id = "AF001", Name = "Atomic Fireball

DocumentDB LINQ query not converting enums correctly

According to this and this, The DocumentDb LINQ provider is supposed to use custom JsonConverters when generating queries that use enums (as far back as version 1.10.0). But we're not seeing that behavior. My project is referencing Microsoft.Azure.DocumentDb 1.13.1 and we're still seeing a LINQ query that converts an enum to its numeric value. A Where() predicate like this request => request.Source == sourceId && request.State == state generates a query like this {SELECT * FROM

Linq Fix to assigning value to anonymous type

In the query below I created new variables with anonymous type. var sampleDetailsList = (from detailsA in context.SampleDetailsA join detailsB in context.SampleDetailsB on new { Key1 = detailsA.SampleId, Key2 = detailsA.Main.Year } equals new { Key1 = detailsB.Sample

Linq EFCore Querying by a Null Navigation property

So I have a student class which has a navigation property to another table. I simply want to query all students who are both NOT in that table and IN that table var students = context.Students.Include(x => x.Exclusion); var excluded = students.Where(x => x.Exclusion != null); var included = students.Where(x => x.Exclusion == null); Result: students: 9 excluded: 9 So that's wrong... if I .ToList() students, excluded is now 2 which is correct, so I assume navigation property quer

Linq Flatten list of dynamic objects in c#

I have a list of dynamics: var list = new List<dynamic> { Json.Decode(@"{""no"":""001"",""photos"":[""01.jpg"",""02.jpg""]}"), Json.Decode(@"{""no"":""002"",""photos"":[""01.jpg""]}") }; How can i use selectMany to fatten the photos property into: {"no": "001", "photo": "01.jpg"} {"no": "001", "photo": "02.jpg"} {"no": "002", "photo": "01.jpg"}

  1    2   3   4   5   6  ... 下一页 最后一页 共 37 页