Search Results

Search found 87713 results on 3509 pages for 'new linq baby'.

Page 7/3509 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Linq is returning too many results when joined

    - by KallDrexx
    In my schema I have two database tables. relationships and relationship_memberships. I am attempting to retrieve all the entries from the relationship table that have a specific member in it, thus having to join it with the relationship_memberships table. I have the following method in my business object: public IList<DBMappings.relationships> GetRelationshipsByObjectId(int objId) { var results = from r in _context.Repository<DBMappings.relationships>() join m in _context.Repository<DBMappings.relationship_memberships>() on r.rel_id equals m.rel_id where m.obj_id == objId select r; return results.ToList<DBMappings.relationships>(); } _Context is my generic repository using code based on the code outlined here. The problem is I have 3 records in the relationships table, and 3 records in the memberships table, each membership tied to a different relationship. 2 membership records have an obj_id value of 2 and the other is 3. I am trying to retrieve a list of all relationships related to object #2. When this linq runs, _context.Repository<DBMappings.relationships>() returns the correct 3 records and _context.Repository<DBMappings.relationship_memberships>() returns 3 records. However, when the results.ToList() executes, the resulting list has 2 issues: 1) The resulting list contains 6 records, all of type DBMappings.relationships(). Upon further inspection there are 2 for each real relationship record, both are an exact copy of each other. 2) All relationships are returned, even if m.obj_id == 3, even though objId variable is correctly passed in as 2. Can anyone see what's going on because I've spent 2 days looking at this code and I am unable to understand what is wrong. I have joins in other linq queries that seem to be working great, and my unit tests show that they are still working, so I must be doing something wrong with this. It seems like I need an extra pair of eyes on this one :)

    Read the article

  • Using conditionals in Linq Programatically

    - by Mike B
    I was just reading a recent question on using conditionals in Linq and it reminded me of an issue I have not been able to resolve. When building Linq to SQL queries programatically how can this be done when the number of conditionals is not known until runtime? For instance in the code below the first clause creates an IQueryable that, if executed, would select all the tasks (called issues) in the database, the 2nd clause will refine that to just issues assigned to one department if one has been selected in a combobox (Which has it's selected item bound to the departmentToShow property). How could I do this using the selectedItems collection instead? IQueryable<Issue> issuesQuery; // Will select all tasks issuesQuery = from i in db.Issues orderby i.IssDueDate, i.IssUrgency select i; // Filters out all other Departments if one is selected if (departmentToShow != "All") { issuesQuery = from i in issuesQuery where i.IssDepartment == departmentToShow select i; } By the way, the above code is simplified, in the actual code there are about a dozen clauses that refine the query based on the users search and filter settings.

    Read the article

  • EF/LINQ: Where() against a property of a subtype

    - by ladenedge
    I have a set of POCOs, all of which implement the following simple interface: interface IIdObject { int Id { get; set; } } A subset of these POCOs implement this additional interface: interface IDeletableObject : IIdObject { bool IsDeleted { get; set; } } I have a repository hierarchy that looks something like this: IRepository<T <: BasicRepository<T <: ValidatingRepository<T (where T is IIdObject) I'm trying to add a FilteringRepository to the hierarchy such that all of the POCOs that implement IDeletableObject have a Where(p => p.IsDeleted == false) filter applied before any other queries take place. My goal is to avoid duplicating the hierarchy solely for IDeletableObjects. My first attempt looked like this: public override IQueryable<T> Query() { return base.Query().Where(t => ((IDeletableObject)t).IsDeleted == false); } This works well with LINQ to Objects, but when I switch to an EF backend I get: "LINQ to Entities only supports casting Entity Data Model primitive types." I went on to try some fancier parameterized solutions, but they ultimately failed because I couldn't make T covariant in the following case for some reason I don't quite understand: interface IQueryFilter<out T> // error { Expression<Func<T, bool>> GetFilter(); } I'd be happy to go into more detail on my more complicated solutions if it would help, but I think I'll stop here for now in hope that someone might have an idea for me to try. Thanks very much in advance!

    Read the article

  • Delaying LINQ to SQL Select Query Execution

    - by Maxim Z.
    I'm building an ASP.NET MVC site that uses LINQ to SQL. In my search method that has some required and some optional parameters, I want to build a LINQ query while testing for the existence of those optional parameters. Here's what I'm currently thinking: using(var db = new DBDataContext()) { IQueryable<Listing> query = null; //Handle required parameter query = db.Listings.Where(l => l.Lat >= form.bounds.extent1.latitude && l.Lat <= form.bounds.extent2.latitude); //Handle optional parameter if (numStars != null) query = query.Where(l => l.Stars == (int)numStars); //Other parameters... //Execute query (does this happen here?) var result = query.ToList(); //Process query... Will this implementation "bundle" the where clauses and then execute the bundled query? If not, how should I implement this feature? Also, is there anything else that I can improve? Thanks in advance.

    Read the article

  • LINQ to objects: Is there

    - by Charles
    I cannot seem to find a way to have LINQ return the value from a specified accessor. I know the name of the accessors for each object, but am unsure if it is possible to pass the requested accessor as a variable or otherwise achieve the desired refactoring. Consider the following code snippet: // "value" is some object with accessors like: format, channels, language row = new List<String> { String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.format).ToArray()), String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.channels).ToArray()), String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.language).ToArray()), // ... } I'd like to refactor this into a method that uses the specified accessor, or perhaps pass a delegate, though I don't see how that could work. string niceRefactor(myObj myObject, string /* or whatever type */ ____ACCESSOR) { return String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.____ACCESSOR).ToArray()); } I have written a decent amount of C#, but am still new to the magic of LINQ. Is this the right approach? How would you refactor this?

    Read the article

  • LINQ to SQL: Reusable expression for property?

    - by coenvdwel
    Pardon me for being unable to phrase the title more exact. Basically, I have three LINQ objects linked to tables. One is Product, the other is Company and the last is a mapping table Mapping to store what Company sells which products and by which ID this Company refers to this Product. I am now retrieving a list of products as follows: var options = new DataLoadOptions(); options.LoadWith<Product>(p => p.Mappings); context.LoadOptions = options; var products = ( from p in context.Products select new { ProductID = p.ProductID, //BackendProductID = p.BackendProductID, BackendProductID = (p.Mappings.Count == 0) ? "None" : (p.Mappings.Count > 1) ? "Multiple" : p.Mappings.First().BackendProductID, Description = p.Description } ).ToList(); This does a single query retrieving the information I want. But I want to be able to move the logic behind the BackendProductID into the LINQ object so I can use the commented line instead of the annoyingly nested ternary operator statements for neatness and re-usability. So I added the following property to the Product object: public string BackendProductID { get { if (Mappings.Count == 0) return "None"; if (Mappings.Count > 1) return "Multiple"; return Mappings.First().BackendProductID; } } The list is still the same, but it now does a query for every single Product to get it's BackendProductID. The code is neater and re-usable, but the performance now is terrible. What I need is some kind of Expression or Delegate but I couldn't get my head around writing one. It always ended up querying for every single product, still. Any help would be appreciated!

    Read the article

  • Linq generic Expression in query on "element" or on IQueryable (multiple use)

    - by Bogdan Maxim
    Hi, I have the following expression public static Expression<Func<T, bool>> JoinByDateCheck<T>(T entity, DateTime dateToCheck) where T : IDateInterval { return (entityToJoin) => entityToJoin.FromDate.Date <= dateToCheck.Date && (entityToJoin.ToDate == null || entityToJoin.ToDate.Value.Date >= dateToCheck.Date); } IDateInterval interface is defined like this: interface IDateInterval { DateTime FromDate {get;} DateTime? ToDate {get;} } and i need to apply it in a few ways: (1) Query on Linq2Sql Table: var q1 = from e in intervalTable where FunctionThatCallsJoinByDateCheck(e, constantDateTime) select e; or something like this: intervalTable.Where(FunctionThatCallsJoinByDateCheck(e, constantDateTime)) (2) I need to use it in some table joins (as linq2sql doesn't provide comparative join): var q2 = from e1 in t1 join e2 in t2 on e1.FK == e2.PK where OtherFunctionThatCallsJoinByDateCheck(e2, e1.FromDate) or var q2 = from e1 in t1 from e2 in t2 where e1.FK == e2.PK && OtherFunctionThatCallsJoinByDateCheck(e2, e1.FromDate) (3) I need to use it in some queries like this: var q3 = from e in intervalTable.FilterFunctionThatCallsJoinByDateCheck(constantDate); Dynamic linq is not something that I can use, so I have to stick to plain linq. Thank you Clarification: Initially I had just the last method (FilterFunctionThatCallsJoinByDateCheck(this IQueryable<IDateInterval> entities, DateTime dateConstant) ) that contained the code from the expression. The problem is that I get a SQL Translate exception if I write the code in a method and call it like that. All I want is to extend the use of this function to the where clause (see the second query in point 2)

    Read the article

  • LINQ to SQL Queries odd Materialization

    - by ptoinson
    I ran across an interesting Linq to SQL, uh, feature, the other day. Perhaps someone can give me a logical explanation for the reasoning behind the results. Take the code below as my example which utilizes the AdventureWorks database setup in a Linq to SQL DataContext. This is a clip from my unit test. The resulting customer returned from a call to both CustomerQuery_Test_01() and CustomerQuery_Test_02() is the same. However, the query executed on the SQLServer are different is a major way. The method CustomerQuery_Test_01 us causing the entire Customer table to be materialized, which the call to CustomerQuery_Test_02 is only causing the single customer to be materialized. The resulting SQL Queries are at the bottom of this post. Anyone have a good reason for this? To me, it was highly non-intuitive. protected virtual Customer GetByPrimaryKey(Func<Customer, bool> keySelection) { AdventureWorksDataContext context = new AdventureWorksDataContext(); return (from r in context.Customers select r).SingleOrDefault(keySelection); } [TestMethod] public void CustomerQuery_Test_01() { Customer customer = GetByPrimaryKey(c => c.CustomerID == 2); } [TestMethod] public void CustomerQuery_Test_02() { AdventureWorksDataContext context = new AdventureWorksDataContext(); Customer customer = (from r in context.Customers select r).SingleOrDefault(c => c.CustomerID == 2); } Query for CustomerQuery_Test_01 (notice the lack of a where clause) SELECT [t0].[CustomerID], [t0].[NameStyle], [t0].[Title], [t0].[FirstName], [t0].[MiddleName], [t0].[LastName], [t0].[Suffix], [t0].[CompanyName], [t0].[SalesPerson], [t0].[EmailAddress], [t0].[Phone], [t0].[PasswordHash], [t0].[PasswordSalt], [t0].[rowguid], [t0].[ModifiedDate] FROM [SalesLT].[Customer] AS [t0] Query for CustomerQuery_Test_02 (notice the where clause) SELECT [t0].[CustomerID], [t0].[NameStyle], [t0].[Title], [t0].[FirstName], [t0].[MiddleName], [t0].[LastName], [t0].[Suffix], [t0].[CompanyName], [t0].[SalesPerson], [t0].[EmailAddress], [t0].[Phone], [t0].[PasswordHash], [t0].[PasswordSalt], [t0].[rowguid], [t0].[ModifiedDate] FROM [SalesLT].[Customer] AS [t0] WHERE [t0].[CustomerID] = @p0

    Read the article

  • LINQ 2 Entities , howto check DateTime.HasValue within the linq query

    - by Snoop Dogg
    Hi all ... I have this method that is supposed to get the latest messages posted, from the Table (& EntitySet) called ENTRY ///method gets "days" as parameter, used in new TimeSpan(days,0,0,0);!! using (Entities db = new Entities()) { var entries = from ent in db.ENTRY where ent.DATECREATE.Value > DateTime.Today.Subtract(new TimeSpan(days, 0, 0, 0)) select new ForumEntryGridView() { id = ent.id, baslik = ent.header, tarih = ent.entrydate.Value, membername = ent.Member.ToString() }; return entries.ToList<ForumEntryGridView>(); } Here the DATECREATED is Nullable in the database. I cant place "if"s in this query ... any way to check for that? Thx in advance

    Read the article

  • Unable to add item to dataset in Linq to SQL

    - by Mike B
    I am having an issue adding an item to my dataset in Linq to SQL. I am using the exact same method in other tables with no problem. I suspect I know the problem but cannot find an answer (I also suspect all i really need is the right search term for Google). Please keep in mind this is a learning project (Although it is in use in a business) I have posted my code and datacontext below. What I am doing is: Create a view model (Relevant bits are shown) and a simple wpf window that allows editing of 3 properties that are bound to the category object. Category is from the datacontext. Edit works fine but add does not. If I check GetChangeSet() just before the db.submitChanges() call there are no adds, edits or deletes. I suspect an issue with the fact that a Category added without a Subcategory would be an orphan but I cannot seem to find the solution. Command code to open window: CategoryViewModel vm = new CategoryViewModel(); AddEditCategoryWindow window = new AddEditCategoryWindow(vm); window.ShowDialog(); ViewModel relevant stuff: public class CategoryViewModel : ViewModelBase { public Category category { get; set; } // Constructor used to Edit a Category public CategoryViewModel(Int16 categoryID) { db = new OITaskManagerDataContext(); category = QueryCategory(categoryID); } // Constructor used to Add a Category public CategoryViewModel() { db = new OITaskManagerDataContext(); category = new Category(); } } The code for saving changes: // Don't close window unless all controls are validated if (!vm.IsValid(this)) return; var changes = vm.db.GetChangeSet(); // DEBUG try { vm.db.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException) { vm.db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges); vm.db.SubmitChanges(); } The Xaml (Edited fror brevity): <TextBox Text="{Binding category.CatName, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding category.CatDescription, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" /> <CheckBox IsChecked="{Binding category.CatIsInactive, Mode=TwoWay}" /> IssCategory in the Issues table is the old, text based category. This field is no longer used and will be removed from the database as soon as this is working and pushed live.

    Read the article

  • Union,Except and Intersect operator in Linq

    - by Jalpesh P. Vadgama
    While developing a windows service using Linq-To-SQL i was in need of something that will intersect the two list and return a list with the result. After searching on net i have found three great use full operators in Linq Union,Except and Intersect. Here are explanation of each operator. Union Operator: Union operator will combine elements of both entity and return result as third new entities. Except Operator: Except operator will remove elements of first entities which elements are there in second entities and will return as third new entities. Intersect Operator: As name suggest it will return common elements of both entities and return result as new entities. Let’s take a simple console application as  a example where i have used two string array and applied the three operator one by one and print the result using Console.Writeline. Here is the code for that. C#, using GeSHi 1.0.8.6 using System; using System.Collections.Generic; using System.Linq; using System.Text;     namespace ConsoleApplication1 {     class Program     {         static void Main(string[] args)         {             string[] a = { "a", "b", "c", "d" };             string[] b = { "d","e","f","g"};               var UnResult = a.Union(b);             Console.WriteLine("Union Result");               foreach (string s in UnResult)             {                 Console.WriteLine(s);                          }               var ExResult = a.Except(b);             Console.WriteLine("Except Result");             foreach (string s in ExResult)             {                 Console.WriteLine(s);             }               var InResult = a.Intersect(b);             Console.WriteLine("Intersect Result");             foreach (string s in InResult)             {                 Console.WriteLine(s);             }             Console.ReadLine();                        }          } }   Parsed in 0.022 seconds at 45.54 KB/s Here is the output of console application as Expected. Hope this will help you.. Technorati Tags: Linq,Except,InterSect,Union,C#

    Read the article

  • Using set operation in LINQ

    - by vik20000in
    There are many set operation that are required to be performed while working with any kind of data. This can be done very easily with the help of LINQ methods available for this functionality. Below are some of the examples of the set operation with LINQ. Finding distinct values in the set of data. We can use the distinct method to find out distinct values in a given list.     int[] factorsOf300 = { 2, 2, 3, 5, 5 };     var uniqueFactors = factorsOf300.Distinct(); We can also use the set operation of UNION with the help of UNION method in the LINQ. The Union method takes another collection as a parameter and returns the distinct union values in  both the list. Below is an example.     int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };    int[] numbersB = { 1, 3, 5, 7, 8 };    var uniqueNumbers = numbersA.Union(numbersB); We can also get the set operation of INTERSECT with the help of the INTERSECT method. Below is an example.     int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };     int[] numbersB = { 1, 3, 5, 7, 8 };         var commonNumbers = numbersA.Intersect(numbersB);  We can also find the difference between the 2 sets of data with the help of except method.      int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };     int[] numbersB = { 1, 3, 5, 7, 8 };         IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB);  Vikram

    Read the article

  • Linq to SQL Lazy Loading in ASP.Net applications

    - by nikolaosk
    In this post I would like to talk about LINQ to SQL and its native lazy loading functionality. I will show you how you can change this behavior. We will create a simple ASP.Net application to demonstrate this. I have seen a lot of people struggling with performance issues. That is mostly due to the lack of knowledge of how LINQ internally works.Imagine that we have two tables Products and Suppliers (Northwind database). There is one to many relationship between those tables-entities. One supplier...(read more)

    Read the article

  • Flattening a Jagged Array with LINQ

    - by PSteele
    Today I had to flatten a jagged array.  In my case, it was a string[][] and I needed to make sure every single string contained in that jagged array was set to something (non-null and non-empty).  LINQ made the flattening very easy.  In fact, I ended up making a generic version that I could use to flatten any type of jagged array (assuming it's a T[][]): private static IEnumerable<T> Flatten<T>(IEnumerable<T[]> data) { return from r in data from c in r select c; } Then, checking to make sure the data was valid, was easy: var flattened = Flatten(data); bool isValid = !flattened.Any(s => String.IsNullOrEmpty(s)); You could even use method grouping and reduce the validation to: bool isValid = !flattened.Any(String.IsNullOrEmpty); Technorati Tags: .NET,LINQ,Jagged Array

    Read the article

  • LINQ Style preference

    - by Erin
    I have come to use LINQ in my every day programming a lot. In fact, I rarely, if ever, use an explicit loop. I have, however, found that I don't use the SQL like syntax anymore. I just use the extension functions. So rather then saying: from x in y select datatransform where filter I use: x.Where(c => filter).Select(c => datatransform) Which style of LINQ do you prefer and what are others on your team are comfortable with?

    Read the article

  • Locking a table for getting MAX in LINQ

    - by Hossein Margani
    Hi Every one! I have a query in LINQ, I want to get MAX of Code of my table and increase it and insert new record with new Code. just like the IDENTITY feature of SQL Server, but here my Code column is char(5) where can be alphabets and numeric. My problem is when inserting a new row, two concurrent processes get max and insert an equal Code to the record. my command is: var maxCode = db.Customers.Select(c=>c.Code).Max(); var anotherCustomer = db.Customers.Where(...).SingleOrDefault(); anotherCustomer.Code = GenerateNextCode(maxCode); db.SubmitChanges(); I ran this command cross 1000 threads and each updating 200 customers, and used a Transaction with IsolationLevel.Serializable, after two or three execution an error occured: using (var db = new DBModelDataContext()) { DbTransaction tran = null; try { db.Connection.Open(); tran = db.Connection.BeginTransaction(IsolationLevel.Serializable); db.Transaction = tran; . . . . tran.Commit(); } catch { tran.Rollback(); } finally { db.Connection.Close(); } } error: Transaction (Process ID 60) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction. other IsolationLevels generates this error: Row not found or changed. Please help me, thank you.

    Read the article

  • OrderBy and Distinct using LINQ-to-Entities

    - by BlueRaja
    Here is my LINQ query: (from o in entities.MyTable orderby o.MyColumn select o.MyColumn).Distinct(); Here is the result: {"a", "c", "b", "d"} Here is the generated SQL: SELECT [Distinct1].[MyColumn] AS [MyColumn] FROM ( SELECT DISTINCT [Extent1].[MyColumn] AS [MyColumn] FROM [dbo].[MyTable] AS [Extent1] ) AS [Distinct1] Is this a bug? Where's my ordering, damnit?

    Read the article

  • LINQ to SQL get grouped MIN with JOIN

    - by Ira Rainey
    I'm having trouble with a LINQ to SQL query getting the min value using Visual Basic. Here's the SQL: SELECT RC.AssetID, MIN(RC.RecCode) AS RecCode, JA.EngineerNote from JobAssetRecCode RC JOIN JobAssets JA ON JA.AssetID = RC.AssetID AND JA.JobID = RC.JobID WHERE RC.InspState = 2 AND RC.RecCode > 0 AND RC.JobID = @JobID GROUP BY RC.AssetID, JA.EngineerNote; I seem to be going around in circles here with grouping etc not managing to get it working. Any help would be greatly appreciated.

    Read the article

  • LINQ to SQL select distinct from multiple colums

    - by Morron
    Hi, I'm using LINQ to SQL to select some columns from one table. I want to get rid of the duplicate result also. Dim customer = (From cus In db.Customers Select cus.CustomerId, cus.CustomerName).Distinct Result: 1 David 2 James 1 David 3 Smith 2 James 5 Joe Wanted result: 1 David 2 James 3 Smith 5 Joe Can anyone show me how to get the wanted result? Thanks.

    Read the article

  • Using linq to combine objects

    - by DotnetDude
    I have 2 instances of a class that implements the IEnumerable interface. I would like to create a new object and combine both of them into one. I understand I can use the for..each to do this. Is there a linq/lambda expression way of doing this?

    Read the article

  • Dynamic LINQ OrderBy

    - by John Sheehan
    I found an example in the VS2008 Examples for Dynamic LINQ that allows you to use a sql-like string (e.g. OrderBy("Name, Age DESC")) for ordering. Unfortunately, the method included only works on IQueryable<T>. Is there any way to get this functionality on IEnumerable<T>?

    Read the article

  • Updating multiple tables at the same time in Linq-to-SQL

    - by kiran
    How do I update two tables at the same time using Linq-to-SQL? var z = from a in db.Products join b in db.ProductSubcategories on a.ProductSubcategoryID equals b.ProductSubcategoryID join d in db.ProductCategories on b.ProductCategoryID equals d.ProductCategoryID select new { ProductName = a.Name, ProductCategory = d.Name, ProductSubCategory = b.Name, Cost = a.StandardCost, discontinuedDate = a.DiscontinuedDate, ProductId=a.ProductID };

    Read the article

  • Order by descending is not working on LINQ to Entity

    - by Vinni
    Order by descending is not working on LINQ to Entity In the following Query In place of ascending If I keep descending it is not working. Please help me out var hosters = from e in context.Hosters_HostingProviderDetail where e.ActiveStatusID == pendingStateId orderby e.HostingProviderName ascending select e; return hosters.ToList();

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >