Search Results

Search found 19165 results on 767 pages for 'custom linq providers'.

Page 13/767 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • LINQ-to-entities - Null reference

    - by BlueRaja
    I could swear this was working the other day: var resultSet = (from o in _entities.Table1 where o.Table2.Table3.SomeColumn == SomeProperty select o ).First(); SelectedItem = resultSet.Table2.SomeOtherColumn; I am getting a null reference exception on the last line: resultSet.Table2 is null. Not only am I sure that all the foreign keys and whatnot have the correct values, but I don't see how Table2 could be null, since o.Table2.Table3.SomeColumn == SomeProperty. resultSet is being returned with all its properties set to the correct values, with the exception that Table2 is null.

    Read the article

  • Chain LINQ IQueryable, and end with Stored Procedure

    - by Alex
    I'm chaining search criteria in my application through IQueryable extension methods, e.g.: public static IQueryable<Fish> AtAge (this IQueryable<Fish> fish, Int32 age) { return fish.Where(f => f.Age == age); } However, I also have a full text search stored procedure: CREATE PROCEDURE [dbo].[Fishes_FullTextSearch] @searchtext nvarchar(4000), @limitcount int AS SELECT Fishes.* FROM Fishes INNER JOIN CONTAINSTABLE(Fishes, *, @searchtext, @limitcount) AS KEY_TBL ON Fishes.Id = KEY_TBL.[KEY] ORDER BY KEY_TBL.[Rank] The stored procedure obviously doesn't return IQueryable, however, is it possible to somehow limit the result set for the stored procedure using IQueryable's? I'm envisioning something like .AtAge(5).AboveWeight(100).Fishes_FulltextSearch("abc"). In this case, the fulltext search should execute on a smaller subset of my Fishes table (narrowed by Age and Weight). Is something like this possible? Sample code?

    Read the article

  • Linq Grouping by 2 keys as a one

    - by Evgeny
    Hello! I write a simple OLAP viewer for my web-site. Here are the classes (abstract example): Employee { ID; Name; Roles[]; //What Employee can do } Order { Price; Employee Manager; Employee Executive; //Maybe wrong english. The person which perform order } Employee can be Manager and Executive in the order at the same time. This means that Employee role is not fixed. I have to group orders by employees and finally get IGrouping with Employee key. So .GroupBy(el=new {el.Manager,el.Executive}) is not allowed. I considered some tricks with IEqualityComparable, but found no solution. If somrbody will help I'll be vary glad, thank you.

    Read the article

  • linq-to-sql combine .any expression

    - by Victor
    I need to filter out parent by property value of child collection. I am doing something like this: var results = (from c in db.Customers where c.Orders.Any(o => o.Status = (int)Status.Ordered) select c; It's fine but now I need to filter by 2 values, i.e. take all parent records that have any chilren records that have BOTH values: var results = (from c in db.Customers where c.Orders.Any(o => o.Status == (int)Status.Ordered) && (o.Status == (int).Shipped)) select c; Trying something obvious like this doesn't work.

    Read the article

  • Linq to Entity Left Outer Join

    - by radman
    Hi All, I have an Entity model with Invoices, AffiliateCommissions and AffiliateCommissionPayments. Invoice to AffiliateCommission is a one to many, AffiliateCommission to AffiliateCommissionPayment is also a one to many I am trying to make a query that will return All Invoices that HAVE a commission but not necessarily have a related commissionPayment. I want to show the invoices with commissions whether they have a commission payment or not. Query looks something like: using (var context = new MyEntitities()) { var invoices = from i in context.Invoices from ac in i.AffiliateCommissions join acp in context.AffiliateCommissionPayments on ac.affiliateCommissionID equals acp.AffiliateCommission.affiliateCommissionID where ac.Affiliate.affiliateID == affiliateID select new { companyName = i.User.companyName, userName = i.User.fullName, email = i.User.emailAddress, invoiceEndDate = i.invoicedUntilDate, invoiceNumber = i.invoiceNumber, invoiceAmount = i.netAmount, commissionAmount = ac.amount, datePaid = acp.paymentDate, checkNumber = acp.checkNumber }; return invoices.ToList(); } This query above only returns items with an AffiliateCommissionPayment.

    Read the article

  • How to get the last element by date of each "type" in LINQ or TSQL

    - by Mauro
    Imagine to have a table defined as CREATE TABLE [dbo].[Price]( [ID] [int] NOT NULL, [StartDate] [datetime] NOT NULL, [Price] [int] NOT NULL ) where ID is the identifier of an action having a certain Price. This price can be updated if necessary by adding a new line with the same ID, different Price, and a more recent date. So with a set of a data like ID StartDate Price 1 01/01/2009 10 1 01/01/2010 20 2 01/01/2009 10 2 01/01/2010 20 How to obtain a set like the following? 1 01/01/2010 20 2 01/01/2010 20

    Read the article

  • Advanced Linq query using into

    - by dilbert789
    I have this query that someone else wrote, it's over my head so I'm looking for some direction. What is happening currently is that it's taking numbers where there is a goal and no history entered, or history and no goal, this screws up the calculations as both goal and history for the same item are required on each. The three tables involved are: KPIType Goal KPIHistory What I need: Need all rows from KPIType. Need all goals where there is a matching KPIHistory row (Goal.KPItypeID == KPIHistory.KPItypeID ) into results 1 Need all kpiHistory’s where there is a matching Goal row (Goal.KPItypeID == KPIHistory.KPItypeID ) into results 2 Current query: var query = from t in dcs.KPIType.Where(k => k.ID <= 23) join g in dcs.Goal.Where(g => g.Dealership.ID == dealershipID && g.YearMonth >= beginDate && g.YearMonth <= endDate ) on t.ID equals g.KPITypeID into results1 join h in dcs.KPIHistory.Where(h => h.Dealership.ID == dealershipID && h.ForDate >= beginDate && h.ForDate <= endDate ) on t.ID equals h.KPIType.ID into results2 orderby t.DisplayOrder select new { t, Goal = results1, KPIHistory = results2 }; query.ToList().ForEach(q => { results.Add(q.t); }); Thanks, I'm happy to answer questions if more info needed.

    Read the article

  • LINQ to SQL:DataContext.SubmitChanges not updating immediately

    - by aximili
    I have a funny problem. Doing DataContext.SubmitChanges() updates Count() in one way but not in the other, see my comment in the code below.(DC is the DataContext) var compliances = c.DataCompliances.Where(x => x.ComplianceCriteria.FKElement == e.Id); if (compliances.Count() == 0) // Insert if not exists { DC.DataCompliances.InsertOnSubmit(new DataCompliance { FKCompany = c.Id, FKComplianceCriteria = criteria.Id }); DC.SubmitChanges(); compliances = c.DataCompliances.Where(x => x.ComplianceCriteria.FKElement == e.Id); // At this point DC.DataCompliances.Count() has increased, // but compliances.Count() is still 0 // When I refresh the page however, it will be 1 } Why does that happen? I need to update compliances after inserting one. Does anyone have a solution?

    Read the article

  • Complex LINQ paging algorithm

    - by sharepointmonkey
    We have a list of projects that may or may not have a collection of subprojects. Our report needs to contain all the projects except those that are the parent project of a subproject. I need to page this into pages of, say, 25 rows. But if subprojects appear on that page then ALL the subprojects of that project must appear on the same page. So more than 25 items may appear if necessary. I've got as far as var pagedProjects = db.Projects.Where(x => !x.SubProjects.Any()).Skip( (pageNo -1) * pageSize).Take(pageSize); Obviously, this fails the second part of the requirements. As a further pain in the arse, I need to have a pager control on the report. So I'll need to be able to calculate the total number of pages. I could loop through the whole table of projects but the performance will suffer. Can anybody come up with a paged solution? EDIT - I should probably mention that SubProjects joins back onto Projects via a selfreferencing foreign key so the whole lot comes back as an IQueryable<Project>.

    Read the article

  • Difference in linq-to-sql query performance using GenericRespositry

    - by Neil
    Given i have a class like so in my Data Layer public class GenericRepository<TEntity> where TEntity : class { [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)] public IQueryable<TEntity> SelectAll() { return DataContext.GetTable<TEntity>(); } } I would be able to query a table in my database like so from a higher layer using (GenericRepositry<MyTable> mytable = new GenericRepositry<MyTable>()) { var myresult = from m in mytable.SelectAll() where m.IsActive select m; } is this considerably slower than using the usual code in my Data Layer using (MyDataContext ctx = new MyDataContext()) { var myresult = from m in ctx.MyTable where m.IsActive select m; } Eliminating the need to write simple single table selects in the Data layer saves a lot of time, but will i regret it?

    Read the article

  • help with exception handling in linq

    - by stackoverflowuser
    I have the following code to retrieve customer name, total (orders ), sum (order details) for reach customer in Northwind database. The problem with below code is that it raises an exception since a few customers dont have any entry in orders table. I know using the query syntax (join) the exception can be avoided. I want to know if the same can be handled with the extension method syntax. CustomerOrderDataContext db = new CustomerOrderDataContext(); var customerOrders = db.Customers.Select(c => new { CompanyName = c.CompanyName, TotalOrders = c.Orders.Count(), TotalQuantity = c.Orders.SelectMany(o => o.Order_Details).Sum(o=>o.Quantity) });

    Read the article

  • LinQ XML mapping to a generic type

    - by Manuel Navarro
    I´m trying to use an external XML file to map the output from a stored procedure into an instance of a class. The problem is that my class is of a generic type: public class MyValue<T> { public T Value { get; set; } } Searching through a lot of blogs an articles I've managed to get this: <?xml version="1.0" encoding="utf-8" ?> <Database Name="" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007"> <Table Name="MyValue" Member="MyNamespace.MyValue`1" > <Type Name="MyNamespace.MyValue`1"> <Column Name="Category" Member="Value" DbType="VarChar(100)" /> </Type> </Table> <Function Method="GetResourceCategories" Name="myprefix_GetResourceCategories" > <ElementType Name="MyNamespace.MyValue`1"/> </Function> </Database> The MyNamespace.MyValue`1 trick works fine, and the class is recognized. I expect four rows from the stored procedure, and I'm getting four MyValue<string> instances, but the big problem is that the property Value for the all four instances is null. The property is not getting mapped and I don't really get why. Maybe worth noting that the property Value is generic, and that when the mapping is done using attributes it works perfect. Anyone have a clue? BTW the method GetResourceCategories: public ISingleResult<MyValue<string>> GetResourceCategories() { IExecuteResult result = this.ExecuteMethodCall( this, (MethodInfo)MethodInfo.GetCurrentMethod()); return (ISingleResult<MyValue<string>>)result.ReturnValue; }

    Read the article

  • Linq with a long where clause

    - by Jeremy Roberts
    Is there a better way to do this? I tried to loop over the partsToChange collection and build up the where clause, but it ANDs them together instead of ORing them. I also don't really want to explicitly do the equality on each item in the partsToChange list. var partsToChange = new Dictionary<string, string> { {"0039", "Vendor A"}, {"0051", "Vendor B"}, {"0061", "Vendor C"}, {"0080", "Vendor D"}, {"0081", "Vendor D"}, {"0086", "Vendor D"}, {"0089", "Vendor E"}, {"0091", "Vendor F"}, {"0163", "Vendor E"}, {"0426", "Vendor B"}, {"1197", "Vendor B"} }; var items = new List<MaterialVendor>(); foreach (var x in partsToChange) { var newItems = ( from m in MaterialVendor where m.Material.PartNumber == x.Key && m.Manufacturer.Name.Contains(x.Value) select m ).ToList(); items.AddRange(newItems); } Additional info: I am working in LINQPad.

    Read the article

  • Conversion of Linq expressions

    - by Arnis L.
    I'm not sure how exactly argument what I'm trying to achieve, therefore - wrote some code: public class Foo{ public Bar Bar{get;set;} } public class Bar{ public string Fizz{get;set;} } public class Facts{ [Fact] public void fact(){ Assert.Equal(expectedExp(),barToFoo(barExp())); } private Expression<Func<Foo,bool>> expectedExp(){ return f=>f.Bar.Fizz=="fizz"; } private Expression<Func<Bar,bool>> barExp(){ return b=>b.Fizz=="fizz"; } private Expression<Func<Foo,bool>> barToFoo (Expression<Func<Bar,bool>> barExp){ return Voodoo(barExp); //<-------------------------------------------??? } } Is this even possible?

    Read the article

  • c# linq to sql join problem

    - by b0x0rz
    i am trying to do using (UserManagementDataContext context = new UserManagementDataContext()) { var users = from u in context.Users where u.UserEMailAdresses.EMailAddress == "[email protected]" select u; return users.Count(); } however, when i get to: using (UserManagementDataContext context = new UserManagementDataContext()) { var users = from u in context.Users where u.UserEMailAdresses. i do not get offered the EMailAddress name, but rather some neutral default-looking list of options in intelisense. what am i doing wrong? table Users ID bigint NameTitle nvarchar(64) NameFirst nvarchar(64) NameMiddle nvarchar(64) NameLast nvarchar(64) NameSuffix nvarchar(64) Status bigint IsActive bit table UserEMailAddresses ID bigint UserID bigint EMailAddress nvarchar(256) IsPrimary bit IsActive bit obviously, 1 user can have many addresses and so Users.ID and UserEMailAddresses.UserID have a relationship between them: 1 to MANY.

    Read the article

  • Linq qurery with multiple where's

    - by Dan
    I am trying the to query my Status Update repository using the following var result = (from s in _dataContext.StatusUpdates where s.Username == "friend1" && s.Username == "friend2" etc... select s).ToList(); Insead of using s.Username == "friendN" continously is there anyway I can pass a list or array or something like that rather that specifying each one, or can i use a foreach loop in the middle of the query. Thanks

    Read the article

  • Exception handling in Linq to SQL for customers without orders

    - by stackoverflowuser
    I have the following code to retrieve customer name, total (orders ), sum (order details) for reach customer in Northwind database. The problem with below code is that it raises an exception since a few customers dont have any entry in orders table. I know using the query syntax (join) the exception can be avoided. I want to know if the same can be handled with the extension method syntax. var customerOrders = db.Customers .Select(c => new { CompanyName = c.CompanyName, TotalOrders = c.Orders.Count(), TotalQuantity = c.Orders .SelectMany(o => o.Order_Details).Sum(o=>o.Quantity) });

    Read the article

  • LINQ : How to query how to sort result by most similarity/equality

    - by aNui
    I want to do a search for Music instruments which has its informations Name, Category and Origin as I asked in my post. But now I want to sort/group the result by similarity/equality to the keyword such as. If I have the list { Harp, Piano, Drum, Guitar, Guitarrón } and if I queried "p" the result should be { Piano, Harp } but it shows Harp first because of the list's sequence and if I add {Grand Piano} to the list and query "piano" the result shoud be like { Piano, Grand Piano } here's my code static IEnumerable<MInstrument> InstrumentsSearch(IEnumerable<MInstrument> InstrumentsList, string query, MInstrument.Category[] SelectedCategories, MInstrument.Origin[] SelectedOrigins) { var result = InstrumentsList .Where(item => SelectedCategories.Contains(item.category)) .Where(item => SelectedOrigins.Contains(item.origin)) .Where(item => { if ( (" " + item.Name.ToLower()).Contains(" " + query.ToLower()) || item.Name.IndexOf(query) != -1 ) { return true; } return false; } ) .Take(30); return result.ToList<MInstrument>(); } Or the result may be like my old self-invented algorithm that I called "by order of occurence", that is just OK to me. Is there any way to do that, please tell me. Thanks in advance.

    Read the article

  • How to retrieve indentity column vaule after insert using LINQ

    - by Hobey
    Could any of you please show me how to complete the following tasks? // Prepare object to be saved // Note that MasterTable has MasterTableId as a Primary Key and it is an indentity column MasterTable masterTable = new MasterTable(); masterTable.Column1 = "Column 1 Value"; masterTable.Column2 = 111; // Instantiate DataContext DataContext myDataContext = new DataContext("<<ConnectionStrin>>"); // Save the record myDataContext.MasterTables.InsertOnSubmit(masterTable); myDataContext.SubmitChanges(); // ?QUESTION? // Now I need to retrieve the value of MasterTableId for the record just inserted above. Kind Regards

    Read the article

  • Copy Rows in a One to Many with LINQ (2 SQL)

    - by Refracted Paladin
    I have a table that stores a bunch of diagnosis for a single plan. When the users create a new plan I need to copy over all existing diagnosis's as well. I had thought to try the below but this is obviously not correct. I am guessing that I will need to loop through my oldDiagnosis part, but how? Thanks! My Attempt so far... public static void CopyPlanDiagnosis(int newPlanID, int oldPlanID) { using (var context = McpDataContext.Create()) { var oldDiagnosis = from planDiagnosi in context.tblPlanDiagnosis where planDiagnosi.PlanID == oldPlanID select planDiagnosi; var newDiagnosis = new tblPlanDiagnosi { PlanID = newPlanID, DiagnosisCueID = oldDiagnosis.DiagnosisCueID, DiagnosisOther = oldDiagnosis.DiagnosisOther, AdditionalInfo = oldDiagnosis.AdditionalInfo, rowguid = Guid.NewGuid() }; context.tblPlanDiagnosis.InsertOnSubmit(newDiagnosis); context.SubmitChanges(); } }

    Read the article

  • Copy Rows in a One to Many with LINQ to SQL

    - by Refracted Paladin
    I have a table that stores a bunch of diagnosis for a single plan. When the users create a new plan I need to copy over all existing diagnosis's as well. I had thought to try the below but this is obviously not correct. I am guessing that I will need to loop through my oldDiagnosis part, but how? Thanks! My Attempt so far... public static void CopyPlanDiagnosis(int newPlanID, int oldPlanID) { using (var context = McpDataContext.Create()) { var oldDiagnosis = from planDiagnosi in context.tblPlanDiagnosis where planDiagnosi.PlanID == oldPlanID select planDiagnosi; var newDiagnosis = new tblPlanDiagnosi { PlanID = newPlanID, DiagnosisCueID = oldDiagnosis.DiagnosisCueID, DiagnosisOther = oldDiagnosis.DiagnosisOther, AdditionalInfo = oldDiagnosis.AdditionalInfo, rowguid = Guid.NewGuid() }; context.tblPlanDiagnosis.InsertOnSubmit(newDiagnosis); context.SubmitChanges(); } }

    Read the article

  • LINQ to XML: suppressing redundant namespace attribute in child nodes

    - by GSerg
    If a node belongs to a namespace, it's children by default belong to the same namespace. So there's no need to provide an xmlns attribute on each child, which is good. However. If I create two nodes like this: Dim parent = <parent xmlns="http://my.namespace.org"/> Dim child = <child xmlns="http://my.namespace.org">value</child> parent.Add(child) Console.WriteLine(parent.ToString) The result is this: <parent xmlns="http://my.namespace.org"> <child xmlns="http://my.namespace.org">value</child> </parent> But, if create them in a less convenient way: Dim parent = <parent xmlns="http://my.namespace.org"/> Dim child As New XElement(XName.Get("child", "http://my.namespace.org")) With {.Value = "value"} parent.Add(child) Console.WriteLine(parent.ToString) The result is more desirable: <parent xmlns="http://my.namespace.org"> <child>value</child> </parent> Obviously, I'd prefer to use the first way because it is so much more intuitive and easy to code. There's also another reason to not use method 2 -- sometimes I need to create nodes with XElement.Parse, parsing a string that contains an xmlns attribute, which produces exactly same results as method 1. So the question is -- how do I get the pretty output of method 2, creating nodes as in method 1? The only option I see is to create a method that would clone given XElement, effectively recreating it according to method 2 pattern, but that seems ugly. I'm looking for a more obvious solution I overlooked for some reason.

    Read the article

  • LINQ and the use of Repeat and Range operator

    - by vik20000in
    LINQ is also very useful when it comes to generation of range or repetition of data.  We can generate a range of data with the help of the range method.     var numbers =         from n in Enumerable.Range(100, 50)         select new {Number = n, OddEven = n % 2 == 1 ? "odd" : "even"}; The above query will generate 50 records where the record will start from 100 till 149. The query also determines if the number is odd or even. But if we want to generate the same number for multiple times then we can use the Repeat method.     var numbers = Enumerable.Repeat(7, 10); The above query will produce a list with 10 items having the value 7. Vikram

    Read the article

  • Sort method versus OrderBy LINQ extension method

    - by nmarun
    I have a class Product with an Id and a Name as properties. There are multiple ways of getting a list of products to display in sorted/ordered fashion, say, by the Name of the product. The two I’m concerned about here are the Sort and the OrderBy extension method through LINQ and the difference between them. 1: public class Product 2: { 3: public int Id { get; set; } 4: public string Name { get; set; } 5: } Below is the list of products that I’ll be using and is defined somewhere in the Program.cs...(read more)

    Read the article

  • LINQ/LAMBDA filter query by date [on hold]

    - by inquisitive_one
    I'm trying to use LINQ to SQL to retrieve earnings data for a particular date range. Currently the table is set up as follows: Comp Eps Year Quarter IBM .5 2012 2 IBM .65 2012 3 IBM .60 2012 4 IBM .5 2011 2 IBM .7 2013 1 IBM .8 2013 2 Except for Eps, all fields have a data type of string or char. Eps has a data type of double. Here's my code: var myData = myTable .Where(t => t.Comp.Equals("IBM") && Convert.Int32(string.Format("{0}{1}", t.Year, t.Quarter)) <= 20131); I get the following error when I tried that code: Method 'System.String Format(System.String, System.Object, System.Object)' has no supported translation to SQL How can I select all Eps that has a year & quarter less than "20132" using a lambda expression?

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >