Search Results

Search found 18661 results on 747 pages for 'linq to mysql'.

Page 28/747 | < Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >

  • Filter a LINQ query

    - by Jack Marchetti
    Here's my query. var query = from g in dc.Group join gm in dc.GroupMembers on g.ID equals gm.GroupID where gm.UserID == UserID select new { id = g.ID, name = g.Name, pools = (from pool in g.Pool // more stuff to populate pools So I have to perform some filtering, but when I attempt to filter var filter = query.Where(f => f.pools.[no access to list of columns] I can't access any of the items within "pools". Does anyone know how I'm able to access that? What I'd like to do is this: var filterbyGame = query.Where(f = > f.pools.GameName == "TestGame"); Let me know if that's even possible with thew ay I have this setup. Thanks guys.

    Read the article

  • PHP will not delete from MySQL

    - by Michal Kopanski
    For some reason, JavaScript/PHP wont delete my data from MySQL! Here is the rundown of the problem. I have an array that displays all my MySQL entries in a nice format, with a button to delete the entry for each one individually. It looks like this: <?php include("login.php"); //connection to the database $dbhandle = mysql_connect($hostname, $username, $password) or die("<br/><h1>Unable to connect to MySQL, please contact support at [email protected]</h1>"); //select a database to work with $selected = mysql_select_db($dbname, $dbhandle) or die("Could not select database."); //execute the SQL query and return records if (!$result = mysql_query("SELECT `id`, `url` FROM `videos`")) echo 'mysql error: '.mysql_error(); //fetch tha data from the database while ($row = mysql_fetch_array($result)) { ?> <div class="video"><a class="<?php echo $row{'id'}; ?>" href="http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?>">http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?></a><a class="del" href="javascript:confirmation(<? echo $row['id']; ?>)">delete</a></div> <?php } //close the connection mysql_close($dbhandle); ?> The delete button has an href of javascript:confirmation(<? echo $row['id']; ?>) , so once you click on delete, it runs this: <script type="text/javascript"> <!-- function confirmation(ID) { var answer = confirm("Are you sure you want to delete this video?") if (answer){ alert("Entry Deleted") window.location = "delete.php?id="+ID; } else{ alert("No action taken") } } //--> </script> The JavaScript should theoretically pass the 'ID' onto the page delete.php. That page looks like this (and I think this is where the problem is): <?php include ("login.php"); mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); mysql_select_db ($dbname) or die("Unable to connect to database"); mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'"); echo ("Video has been deleted."); ?> If there's anyone out there that may know the answer to this, I would greatly appreciate it. I am also opened to suggestions (for those who aren't sure). Thanks!

    Read the article

  • LINQ to SQL does not update when data has changed in database

    - by aximili
    I have this problem where after a field (say Field3 in table MyTable) is updated on the database, MyTable.Field3 (in C#) is still returning the old value. I suspect there is some caching...? How do I force it to: Read the value from the database? OR Update the value in the MyTable class? Or is there anything I miss? Thank you in advance.

    Read the article

  • Linq to SQL generates StackOverflowException in tight Insert loop

    - by ChrisW
    I'm parsing an XML file and inserting the rows into a table (and related tables) using LinqToSQL. I parse the XML file using LinqToXml into IEnumerable. Then, I create a foreach loop, where I build my LinqToSQL objects and call InsertOnSubmit and SubmitChanges at the end of each loop. Nothing special here. Usually, I make it through around 4,100 records before receiving a StackOverflowException from LinqToSql, right as I call SubmitChanges. It's not always on 4,100... sometimes it's 4102, sometimes, less, etc. I've tried inserting the records that generate the failure individually, but putting them in their own Xml file, but that inserts fine... so it's not the data. I'm running the whole process from an MVC2 app that is uploading the Xml file to the server. I've adjusted my WebRequest timeouts to appropriate values, and again, I'm not getting timeout errors, just StackOverflowExceptions. So is there some pattern that I should follow for times when I have to do many insertions into the database? I never encounter this exception on smaller Xml files, just larger ones.

    Read the article

  • ClassCastExcpetion Linq to SQL

    - by BitFiddler
    I have a column definition in my generated Dbml file: <Column(Storage:="_Low", DbType:="Decimal(18,2)", UpdateCheck:=UpdateCheck.WhenChanged)> Public Property Low() As System.Nullable(Of Decimal) When I try to assign: With someObject .Low = 21.33D End With I get a ClassCastException when I call db_context.SubmitChanges(). Anyone have an idea why this is? Thanks

    Read the article

  • Linq duplicate removal with a twist

    - by Danthar
    I got a list that contains al the status items of each order. The problem that i have is that i need to remove all the items of which the status - logdate combination is not the highest. e.g var inputs = new List<StatusItem>(); //note that the 3th id is simply a modifier that adds that amount of secs //to the current datetime, to make testing easier inputs.Add(new StatusItem(123, 30, 1)); inputs.Add(new StatusItem(123, 40, 2)); inputs.Add(new StatusItem(123, 50, 3)); inputs.Add(new StatusItem(123, 40, 4)); inputs.Add(new StatusItem(123, 50, 5)); inputs.Add(new StatusItem(100, 20, 6)); inputs.Add(new StatusItem(100, 30, 7)); inputs.Add(new StatusItem(100, 20, 8)); inputs.Add(new StatusItem(100, 30, 9)); inputs.Add(new StatusItem(100, 40, 10)); inputs.Add(new StatusItem(100, 50, 11)); inputs.Add(new StatusItem(100, 40, 12)); var l = from i in inputs group i by i.internalId into cg select from s in cg group s by s.statusId into sg select sg.OrderByDescending(n => n.date).First() ; This creates a list that returnes me the following: order 123 status 30 date 4/9/2010 6:44:21 PM order 123 status 40 date 4/9/2010 6:44:24 PM order 123 status 50 date 4/9/2010 6:44:25 PM order 100 status 20 date 4/9/2010 6:44:28 PM order 100 status 30 date 4/9/2010 6:44:29 PM order 100 status 40 date 4/9/2010 6:44:32 PM order 100 status 50 date 4/9/2010 6:44:31 PM This is ALMOST correct. However that last line which has status 50 needs to be filtered out as well because it was overruled by status 40 in the historylist. U can tell by the fact that its date is lower then the "last" status-item with the status 40. I was hoping someone could give me some pointers because im stuck.

    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

  • Dealing with a null datetime element within xml using linq

    - by diver-d
    HI I have an example document that looks like <ItemEntry> <PurchaseDate>2010-03-18T20:36:32.81108+13:00</PurchaseDate> <StoreGUID>0a0324ad-5f99-486a-a2d0-870bc6991e9f</StoreGUID> <ExpiryDate /> <CardID>111111</CardID> <PurchaseAmount>0</PurchaseAmount> <RedeemedAmount /> <EntryType>1</EntryType> <RedeemedDate /> <SalesAssistantID>0</SalesAssistantID> </ItemEntry> As you can see there are couple of elements ExpiryDate and RedeemedDate are are empty. var q = from c in xml.Elements("ItemEntry") select new mdDetail { PurchaseDate = (DateTime)c.Element("PurchaseDate"), StoreGUID = (Guid)c.Element("StoreGUID"), ExpiryDate = (DateTime?)c.Element("ExpiryDate")??DateTime.MinValue, CardID = (int)c.Element("CardID"), PurchaseAmount = (double)c.Element("PurchaseAmount"), RedeemedAmount = (double?)c.Element("RedeemedAmount"), EntryType = (int)c.Element("EntryType"), RedeemedDate = (DateTime?)c.Element("RedeemedDate") ??DateTime.MinValue, SalesAssistantID = (int)c.Element("SalesAssistantID"), } ; foreach (var item in q) { } I am not sure how to deal with the null element value, I have tried ??DateTime.MinValue and ??null however both give me a " String was not recognized as a valid DateTime." error. Any suggestions? Thank you

    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

  • 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-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 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

  • 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

  • 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

  • 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

  • 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 : 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

  • 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

< Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >