Search Results

Search found 436 results on 18 pages for 'iqueryable'.

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

  • LINQ - How to query a range of effective dates that only has start dates

    - by itchi
    I'm using C# 3.5 and EntityFramework. I have a list of items in the database that contain interest rates. Unfortunately this list only contains the Effective Start Date. I need to query this list for all items within a range. However, I can't see a way to do this without querying the database twice. (Although I'm wondering if delayed execution with EntityFramework is making only one call.) Regardless, I'm wondering if I can do this without using my context twice. internal IQueryable<Interest> GetInterests(DateTime startDate, DateTime endDate) { var FirstDate = Context.All().Where(x => x.START_DATE < startDate).Max(x => x.START_DATE); IQueryable<Interest> listOfItems = Context.All().Where(x => x.START_DATE >= FirstDate && x.START_DATE <= endDate); return listOfItems; }

    Read the article

  • How to write this Link2Sql select query

    - by RememberME
    I have 3 tables: subcontracts, companies and contacts. Each table has a active_status flags which shows that the item is still active (hasn't been deleted). Each contact has a company_id field which stores the id of the contact's company. Each subcontract has a company_id field which stores the subcontract's company. Each company has a company_id field which holds its guid and a primary_company field, b/c the company could be a subsidiary. If it's a subsidiary, the primary_company field holds the id of the primary company. I have a subcontract form. On the form, I have a drop-down of contacts which are stored in a contact table. Currently the drop-down lists all contacts. I would like to have the drop-down only list contacts which belong to the subcontract's company or any of that company's subsidiaries. I have the following query which I use elsewhere in the program to pass a company_id and get its subsidiaries. public IQueryable<company> GetSubsidiaryCompanies(Guid id) { return from c in db.companies where c.primary_company == id && c.active_status == true select c; } This is my current contact selection public IQueryable<contact> GetContacts() { return from c in db.contacts where c.active_status == true orderby c.contact_name select c; } What I need to do is pass it the subcontract.company_id and then only return the contacts where contact.company_id == subcontract.company_id or contact.company_id == one of the subsidiary ids.

    Read the article

  • Can't return a List from a Compiled Query.

    - by Andrew
    I was speeding up my app by using compiled queries for queries which were getting hit over and over. I tried to implement it like this: Function Select(ByVal fk_id As Integer) As List(SomeEntity) Using db As New DataContext() db.ObjectTrackingEnabled = False Return CompiledSelect(db, fk_id) End Using End Function Shared CompiledSelect As Func(Of DataContext, Integer, List(Of SomeEntity)) = _ CompiledQuery.Compile(Function(db As DataContext, fk_id As Integer) _ (From u In db.SomeEntities _ Where u.SomeLinkedEntity.ID = fk_id _ Select u).ToList()) This did not work and I got this error message: Type : System.ArgumentNullException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Message : Value cannot be null. Parameter name: value However, when I changed my compiled query to return IQueryable instead of List like so: Function Select(ByVal fk_id As Integer) As List(SomeEntity) Using db As New DataContext() db.ObjectTrackingEnabled = False Return CompiledSelect(db, fk_id).ToList() End Using End Function Shared CompiledSelect As Func(Of DataContext, Integer, IQueryable(Of SomeEntity)) = _ CompiledQuery.Compile(Function(db As DataContext, fk_id As Integer) _ From u In db.SomeEntities _ Where u.SomeLinkedEntity.ID = fk_id _ Select u) It worked fine. Can anyone shed any light as to why this is? BTW, compiled queries rock! They sped up my app by a factor of 2.

    Read the article

  • SubSonic generated code and always filtering records

    - by cmroanirgo
    Hi, I have a table called "Users" that has a column called "deleted", a boolean indicating that the user is "Deleted" from the system (without actually deleting it, of course). I also have a lot of tables that have a FK to the Users.user_id column. Subsonic generates (very nicely) the code for all the foreign keys in a similar manner: public IQueryable<person> user { get { var repo=user.GetRepo(); return from items in repo.GetAll() where items.user_id == _user_id select items; } } Whilst this is good and all, is there a way to generate the code in such a way to always filter out the "Deleted" users too? In the office here, the only suggestion we can think of is to use a partial class and extend it. This is obviously a pain when there are lots and lots of classes using the User table, not to mention the fact that it's easy to inadvertently use the wrong property (User vs ActiveUser in this example): public IQueryable<User> ActiveUser { get { var repo=User.GetRepo(); return from items in repo.GetAll() where items.user_id == _user_id and items.deleted == 0 select items; } } Any ideas?

    Read the article

  • Running an existing LINQ query against a dynamic object (DataTable like)

    - by TomTom
    Hello, I am working on a generic OData provider to go against a custom data provider that we have here. Thsi is fully dynamic in that I query the data provider for the table it knows. I have a basic storage structure in place so far based on the OData sample code. My problem is: OData supports queries and expects me to hand in an IQueryable implementation. On the lowe rside, I dont have any query support. Not a joke - the provider returns tables and the WHERE clause is not supported. Performance is not an issue here - the tables are small. It is ok to sort them in the OData provider. My main problem is this. I submit a SQL statement to get out the data of a table. The result is some sort of ADO.NET data reader here. I need to expose an IQueryable implementation for this data to potentially allow later filtering. Any ide ahow to best touch that? .NET 3.5 only (no 4.0 planned for some time). I was seriously thinking of creating dynamic DTO classes for every table (emitting bytecode) so I can use standard LINQ. Right now I am using a dictionary per entry (not too efficient) but I see no real way to filter / sort based on them.

    Read the article

  • Errors when creating a custom Querable object with MVC and Subsonic pagedlist

    - by minus4
    hiya, i have the following code but when i try and create a new IQuerable i get an error that the interface cannot be implemented, if i take away the new i get a not implemented exception, have had to jump back and work on some old ASP classic sites for past month and for the life of me i can not wake my brain up into C# mode. Could you please have a look at below and give me some clues on where i'm going wrong: The code is to create a list of priceItems, but instead of a categoryID (int) i am going to be showing the name as string. public ActionResult ViewPriceItems(int? page) { var crm = 0; page = GetPage(page); // try and create items2 IQueryable<ViewPriceItemsModel> items2 = new IQueryable<ViewPriceItemsModel>(); // the data to be paged,but unmodified var olditems = PriceItem.All().OrderBy(x => x.PriceItemID); foreach (var item in olditems) { // set category as the name not the ID for easier reading items2.Concat(new [] {new ViewPriceItemsModel {ID = item.PriceItemID, Name = item.PriceItem_Name, Category = PriceCategory.SingleOrDefault( x => x.PriceCategoryID == item.PriceItem_PriceCategory_ID).PriceCategory_Name, Display = item.PriceItems_DisplayMethod}}); } crm = olditems.Count() / MaxResultsPerPage; ViewData["numtpages"] = crm; ViewData["curtpage"] = page + 1; // return a paged result set return View(new PagedList<ViewPriceItemsModel>(items2, page ?? 0, MaxResultsPerPage)); } many thanks

    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

  • Passing filtering functions to Where() in LINQ-to-SQL

    - by Daniel
    I'm trying to write a set of filtering functions that can be chained together to progressively filter a data set. What's tricky about this is that I want to be able to define the filters in a different context from that in which they'll be used. I've gotten as far as being able to pass a very basic function to the Where() clause in a LINQ statement: filters file: Func<item, bool> returnTrue = (i) => true; repository file: public IQueryable<item> getItems() { return DataContext.Items.Where(returnTrue); } This works. However, as soon as I try to use more complicated logic, the trouble begins: filters file: Func<item, bool> isAssignedToUser = (i) => i.assignedUserId == userId; repository file: public IQueryable<item> getItemsAssignedToUser(int userId) { return DataContext.Items.Where(isAssignedToUser); } This won't even build because userId isn't in the same scope as isAssignedToUser(). I've also tried declaring a function that takes the userId as a parameter: Func<item, int, bool> isAssignedToUser = (i, userId) => i.assignedUserId == userId; The problem with this is that it doesn't fit the function signature that Where() is expecting: Func<item, bool> There must be a way to do this, but I'm at a loss for how. I don't feel like I'm explaining this very well, but hopefully you get the gist. Thanks, Daniel

    Read the article

  • Is there a way to use Linq projections with extension methods

    - by Acoustic
    I'm trying to use AutoMapper and a repository pattern along with a fluent interface, and running into difficulty with the Linq projection. For what it's worth, this code works fine when simply using in-memory objects. When using a database provider, however, it breaks when constructing the query graph. I've tried both SubSonic and Linq to SQL with the same result. Thanks for your ideas. Here's an extension method used in all scenarios - It's the source of the problem since everything works fine without using extension methods public static IQueryable<MyUser> ByName(this IQueryable<MyUser> users, string firstName) { return from u in users where u.FirstName == firstName select u; } Here's the in-memory code that works fine var userlist = new List<User> {new User{FirstName = "Test", LastName = "User"}}; Mapper.CreateMap<User, MyUser>(); var result = (from u in userlist select Mapper.Map<User, MyUser>(u)) .AsQueryable() .ByName("Test"); foreach (var x in result) { Console.WriteLine(x.FirstName); } Here's the same thing using a SubSonic (or Linq to SQL or whatever) that fails. This is what I'd like to make work somehow with extension methods... Mapper.CreateMap<User, MyUser>(); var result = from u in new DataClasses1DataContext().Users select Mapper.Map<User, MyUser>(u); var final = result.ByName("Test"); foreach(var x in final) // Fails here when the query graph built. { Console.WriteLine(x.FirstName); } The goal here is to avoid having to manually map the generated "User" object to the "MyUser" domain object- in other words, I'm trying to find a way to use AutoMapper so I don't have this kind of mapping code everywhere a database read operation is needed: var result = from u in new DataClasses1DataContext().Users select new MyUser // Can this be avoided with AutoMapper AND extension methods? { FirstName = v.FirstName, LastName = v.LastName };

    Read the article

  • EF Many-to-many dbset.Include in DAL on GenericRepository

    - by Bryant
    I can't get the QueryObjectGraph to add INCLUDE child tables if my life depended on it...what am I missing? Stuck for third day on something that should be simple :-/ DAL: public abstract class RepositoryBase<T> where T : class { private MyLPL2Context dataContext; private readonly IDbSet<T> dbset; protected RepositoryBase(IDatabaseFactory databaseFactory) { DatabaseFactory = databaseFactory; dbset = DataContext.Set<T>(); DataContext.Configuration.LazyLoadingEnabled = true; } protected IDatabaseFactory DatabaseFactory { get; private set; } protected MyLPL2Context DataContext { get { return dataContext ?? (dataContext = DatabaseFactory.Get()); } } public IQueryable<T> QueryObjectGraph(Expression<Func<T, bool>> filter, params string[] children) { foreach (var child in children) { dbset.Include(child); } return dbset.Where(filter); } ... DAL repositories public interface IBreed_TranslatedSqlRepository : ISqlRepository<Breed_Translated> { } public class Breed_TranslatedSqlRepository : RepositoryBase<Breed_Translated>, IBreed_TranslatedSqlRepository { public Breed_TranslatedSqlRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) {} } BLL Repo: public IQueryable<Breed_Translated> QueryObjectGraph(Expression<Func<Breed_Translated, bool>> filter, params string[] children) { return _r.QueryObjectGraph(filter, children); } Controller: var breeds1 = _breedTranslatedRepository .QueryObjectGraph(b => b.Culture == culture, new string[] { "AnimalType_Breed" }) .ToList(); I can't get to Breed.AnimalType_Breed.AnimalTypeId ..I can drill as far as Breed.AnimalType_Breed then the intelisense expects an expression? Cues if any, DB Tables: bold is many-to-many Breed, Breed_Translated, AnimalType_Breed, AnimalType, ...

    Read the article

  • Moq.Mock<T> - how to setup a method that takes an expression

    - by Paul
    I am Mocking my repository interface and am not sure how to setup a method that takes an expression and returns an object? I am using Moq and NUnit Interface: public interface IReadOnlyRepository : IDisposable { IQueryable<T> All<T>() where T : class; T Single<T>(Expression<Func<T, bool>> expression) where T : class; } Test with IQueryable already setup, but don't know how to setup the T Single: private Moq.Mock<IReadOnlyRepository> _mockRepos; private AdminController _controller; [SetUp] public void SetUp() { var allPages = new List<Page>(); for (var i = 0; i < 10; i++) { allPages.Add(new Page { Id = i, Title = "Page Title " + i, Slug = "Page-Title-" + i, Content = "Page " + i + " on page content." }); } _mockRepos = new Moq.Mock<IReadOnlyRepository>(); _mockRepos.Setup(x => x.All<Page>()).Returns(allPages.AsQueryable()); //Not sure what to do here??? _mockRepos.Setup(x => x.Single<Page>() //---- _controller = new AdminController(_mockRepos.Object); }

    Read the article

  • How can I implement CRUD operations in a base class for an entity framework app?

    - by hminaya
    I'm working a simple EF/MVC app and I'm trying to implement some Repositories to handle my entities. I've set up a BaseObject Class and a IBaseRepository Interface to handle the most basic operations so I don't have to repeat myself each time: public abstract class BaseObject<T> { public XA.Model.Entities.XAEntities db; public BaseObject() { db = new Entities.XAEntities(); } public BaseObject(Entities.XAEntities cont) { db = cont; } public void Delete(T entity) { db.DeleteObject(entity); db.SaveChanges(); } public void Update(T entity) { db.AcceptAllChanges(); db.SaveChanges(); } } public interface IBaseRepository<T> { void Add(T entity); T GetById(int id); IQueryable<T> GetAll(); } But then I find myself having to implement 3 basic methods in every Repository ( Add, GetById & GetAll): public class AgencyRepository : Framework.BaseObject<Agency>, Framework.IBaseRepository<Agency> { public void Add(Agency entity) { db.Companies.AddObject(entity); db.SaveChanges(); } public Agency GetById(int id) { return db.Companies.OfType<Agency>().FirstOrDefault(x => x.Id == id); } public IQueryable<Agency> GetAll() { var agn = from a in db.Companies.OfType<Agency>() select a; return agn; } } How can I get these into my BaseObject Class so I won't run in conflict with DRY.

    Read the article

  • Convert SQL to LINQ in MVC3 with Ninject

    - by Jeff
    I'm using MVC3 and still learning LINQ. I'm having some trouble trying to convert a query to LINQ to Entities. I want to return an employee object. SELECT E.EmployeeID, E.FirstName, E.LastName, MAX(EO.EmployeeOperationDate) AS "Last Operation" FROM Employees E INNER JOIN EmployeeStatus ES ON E.EmployeeID = ES.EmployeeID INNER JOIN EmployeeOperations EO ON ES.EmployeeStatusID = EO.EmployeeStatusID INNER JOIN Teams T ON T.TeamID = ES.TeamID WHERE T.TeamName = 'MyTeam' GROUP BY E.EmployeeID, E.FirstName, E.LastName ORDER BY E.FirstName, E.LastName What I have is a few tables, but I need to get only the newest status based on the EmployeeOpertionDate. This seems to work fine in SQL. I'm also using Ninject and set my query to return Ienumerable. I played around with the group by option but it then returns IGroupable. Any guidance on converting and returning the property object type would be appreciated. Edit: I started writing this out in LINQ but I'm not sure how to properly return the correct type or cast this. public IQueryable<Employee> GetEmployeesByTeam(int teamID) { var q = from E in context.Employees join ES in context.EmployeeStatuses on E.EmployeeID equals ES.EmployeeID join EO in context.EmployeeOperations on ES.EmployeeStatusID equals EO.EmployeeStatusID join T in context.Teams on ES.TeamID equals T.TeamID where T.TeamName == "MyTeam" group E by E.EmployeeID into G select G; return q; } Edit2: This seems to work for me public IQueryable<Employee> GetEmployeesByTeam(int teamID) { var q = from E in context.Employees join ES in context.EmployeeStatuses on E.EmployeeID equals ES.EmployeeID join EO in context.EmployeeOperations.OrderByDescending(eo => eo.EmployeeOperationDate) on ES.EmployeeStatusID equals EO.EmployeeStatusID join T in context.Teams on ES.TeamID equals T.TeamID where T.TeamID == teamID group E by E.EmployeeID into G select G.FirstOrDefault(); return q; }

    Read the article

  • Problem with LINQ query

    - by Niels Bosma
    The following works fine: (from e in db.EnquiryAreas from w in db.WorkTypes where w.HumanId != null && w.SeoPriority > 0 && e.HumanId != null && e.SeoPriority > 0 && db.Enquiries.Where(f => f.WhereId == e.Id && f.WhatId == w.Id && f.EnquiryPublished != null && f.StatusId != EnquiryMethods.STATUS_INACTIVE && f.StatusId != EnquiryMethods.STATUS_REMOVED && f.StatusId != EnquiryMethods.STATUS_REJECTED && f.StatusId != EnquiryMethods.STATUS_ATTEND ).Any() select new { EnquiryArea = e, WorkType = w }); But: (from e in db.EnquiryAreas from w in db.WorkTypes where w.HumanId != null && w.SeoPriority > 0 && e.HumanId != null && e.SeoPriority > 0 && EnquiryMethods.BlockOnSite(db.Enquiries.Where(f => f.WhereId == e.Id && f.WhatId == w.Id)).Any() select new { EnquiryArea = e, WorkType = w }); + public static IQueryable<Enquiry> BlockOnSite(IQueryable<Enquiry> linq) { return linq.Where(e => e.EnquiryPublished != null && e.StatusId != STATUS_INACTIVE && e.StatusId != STATUS_REMOVED && e.StatusId != STATUS_REJECTED && e.StatusId != STATUS_ATTEND ); } I get the following error: base {System.SystemException}: {"Method 'System.Linq.IQueryable1[X.Enquiry] BlockOnSite(System.Linq.IQueryable1[X.Enquiry])' has no supported translation to SQL."}

    Read the article

  • Field Members vs Method Variables?

    - by Braveyard
    Recently I've been thinking about performance difference between class field members and method variables. What exactly I mean is in the example below : Lets say we have a DataContext object for Linq2SQL class DataLayer { ProductDataContext context = new ProductDataContext(); public IQueryable<Product> GetData() { return context.Where(t=>t.ProductId == 2); } } In the example above, context will be stored in heap and the GetData method variables will be removed from Stack after Method is executed. So lets examine the following example to make a distinction : class DataLayer { public IQueryable<Product> GetData() { ProductDataContext context = new ProductDataContext(); return context.Where(t=>t.ProductId == 2); } } (*1) So okay first thing we know is if we define ProductDataContext instance as a field, we can reach it everywhere in the class which means we don't have to create same object instance all the time. But lets say we are talking about Asp.NET and once the users press submit button the post data is sent to the server and the events are executed and the posted data stored in a database via the method above so it is probable that the same user can send different data after one another.If I know correctly after the page is executed, the finalizers come into play and clear things from memory (from heap) and that means we lose our instance variables from memory as well and after another post, DataContext should be created once again for the new page cycle. So it seems the only benefit of declaring it publicly to the whole class is the just number one text above. Or is there something other? Thanks in advance... (If I told something incorrect please fix me.. )

    Read the article

  • Why can't you return a List from a Compiled Query?

    - by Andrew
    I was speeding up my app by using compiled queries for queries which were getting hit over and over. I tried to implement it like this: Function Select(ByVal fk_id As Integer) As List(SomeEntity) Using db As New DataContext() db.ObjectTrackingEnabled = False Return CompiledSelect(db, fk_id) End Using End Function Shared CompiledSelect As Func(Of DataContext, Integer, List(Of SomeEntity)) = _ CompiledQuery.Compile(Function(db As DataContext, fk_id As Integer) _ (From u In db.SomeEntities _ Where u.SomeLinkedEntity.ID = fk_id _ Select u).ToList()) This did not work and I got this error message: Type : System.ArgumentNullException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Message : Value cannot be null. Parameter name: value However, when I changed my compiled query to return IQueryable instead of List like so: Function Select(ByVal fk_id As Integer) As List(SomeEntity) Using db As New DataContext() db.ObjectTrackingEnabled = False Return CompiledSelect(db, fk_id).ToList() End Using End Function Shared CompiledSelect As Func(Of DataContext, Integer, IQueryable(Of SomeEntity)) = _ CompiledQuery.Compile(Function(db As DataContext, fk_id As Integer) _ From u In db.SomeEntities _ Where u.SomeLinkedEntity.ID = fk_id _ Select u) It worked fine. Can anyone shed any light as to why this is? BTW, compiled queries rock! They sped up my app by a factor of 2.

    Read the article

  • Howto use predicates in LINQ to Entities for Entity Framework objects

    - by user274947
    I'm using LINQ to Entities for Entity Framework objects in my Data Access Layer. My goal is to filter as much as I can from the database, without applying filtering logic on in-memory results. For that purpose Business Logic Layer passes a predicate to Data Access Layer. I mean Func<MyEntity, bool> So, if I use this predicate directly, like public IQueryable<MyEntity> GetAllMatchedEntities(Func<MyEntity, Boolean> isMatched) { return qry = _Context.MyEntities.Where(x => isMatched(x)); } I'm getting the exception [System.NotSupportedException] --- {"The LINQ expression node type 'Invoke' is not supported in LINQ to Entities."} Solution in that question suggests to use AsExpandable() method from LINQKit library. But again, using public IQueryable<MyEntity> GetAllMatchedEntities(Func<MyEntity, Boolean> isMatched) { return qry = _Context.MyEntities.AsExpandable().Where(x => isMatched(x)); } I'm getting the exception Unable to cast object of type 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.LambdaExpression' Is there way to use predicate in LINQ to Entities query for Entity Framework objects, so that it is correctly transformed it into a SQL statement. Thank you.

    Read the article

  • return Queryable<T> or List<T> in a Repository<T>

    - by Danny Chen
    Currently I'm building an windows application using sqlite. In the data base there is a table say User, and in my code there is a Repository<User> and a UserManager. I think it's a very common design. In the repository there is a List method: //Repository<User> class public List<User> List(where, orderby, topN parameters and etc) { //query and return } This brings a problem, if I want to do something complex in UserManager.cs: //UserManager.cs public List<User> ListUsersWithBankAccounts() { var userRep = new UserRepository(); var bankRep = new BankAccountRepository(); var result = //do something complex, say "I want the users live in NY //and have at least two bank accounts in the system } You can see, returning List<User> brings performance issue, becuase the query is executed earlier than expected. Now I need to change it to something like a IQueryable<T>: //Repository<User> class public TableQuery<User> List(where, orderby, topN parameters and etc) { //query and return } TableQuery<T> is part of the sqlite driver, which is almost equals to IQueryable<T> in EF, which provides a query and won't execute it immediately. But now the problem is: in UserManager.cs, it doesn't know what is a TableQuery<T>, I need to add new reference and import namespaces like using SQLite.Query in the business layer project. It really brings bad code feeling. Why should my business layer know the details of the database? why should the business layer know what's SQLite? What's the correct design then?

    Read the article

  • Using Linq-To-SQL I'm getting some weird behavior doing text searches with the .Contains method. Loo

    - by Nate Bross
    I have a table, where I need to do a case insensitive search on a text field. If I run this query in LinqPad directly on my database, it works as expected Table.Where(tbl => tbl.Title.Contains("StringWithAnyCase")) // also, adding in the same constraints I'm using in my repository works in LinqPad // Table.Where(tbl => tbl.Title.Contains("StringWithAnyCase") && tbl.IsActive == true) In my application, I've got a repository which exposes IQueryable objects which does some initial filtering and it looks like this var dc = new MyDataContext(); public IQueryable<Table> GetAllTables() { var ret = dc.Tables.Where(t => t.IsActive == true); return ret; } In the controller (its an MVC app) I use code like this in an attempt to mimic the LinqPad query: var rpo = new RepositoryOfTable(); var tables = rpo.GetAllTables(); // for some reason, this does a CASE SENSITIVE search which is NOT what I want. tables = tables.Where(tbl => tbl.Title.Contains("StringWithAnyCase"); return View(tables); The column is defiend as an nvarchar(50) in SQL Server 2008. Any help or guidance is greatly appreciated!

    Read the article

  • Strongly typed dynamic Linq sorting

    - by David
    I'm trying to build some code for dynamically sorting a Linq IQueryable<. The obvious way is here, which sorts a list using a string for the field name http://dvanderboom.wordpress.com/2008/12/19/dynamically-composing-linq-orderby-clauses/ However I want one change - compile time checking of field names, and the ability to use refactoring/Find All References to support later maintenance. That means I want to define the fields as f=f.Name, instead of as strings. For my specific use I want to encapsulate some code that would decide which of a list of named "OrderBy" expressions should be used based on user input, without writing different code every time. Here is the gist of what I've written: var list = from m Movies select m; // Get our list var sorter = list.GetSorter(...); // Pass in some global user settings object sorter.AddSort("NAME", m=m.Name); sorter.AddSort("YEAR", m=m.Year).ThenBy(m=m.Year); list = sorter.GetSortedList(); ... public class Sorter ... public static Sorter GetSorter(this IQueryable source, ...) The GetSortedList function determines which of the named sorts to use, which results in a List object, where each FieldData contains the MethodInfo and Type values of the fields passed in AddSort: public SorterItem AddSort(Func field) { MethodInfo ... = field.Method; Type ... = TypeOf(TKey); // Create item, add item to diction, add fields to item's List // The item has the ThenBy method, which just adds another field to the List } I'm not sure if there is a way to store the entire field object in a way that would allow it be returned later (it would be impossible to cast, since it is a generic type) Is there a way I could adapt the sample code, or come up with entirely new code, in order to sort using strongly typed field names after they have been stored in some container and retrieved (losing any generic type casting)

    Read the article

  • c# finding matching words in table column using Linq2Sql

    - by David Liddle
    I am trying to use Linq2Sql to return all rows that contain values from a list of strings. The linq2sql class object has a string property that contains words separated by spaces. public class MyObject { public string MyProperty { get; set; } } Example MyProperty values are: MyObject1.MyProperty = "text1 text2 text3 text4" MyObject2.MyProperty = "text2" For example, using a string collection, I pass the below list var list = new List<>() { "text2", "text4" } This would return both items in my example above as they both contain "text2" value. I attempted the following using the below code however, because of my extension method the Linq2Sql cannot be evaluated. public static IQueryable<MyObject> WithProperty(this IQueryable<MyProperty> qry, IList<string> p) { return from t in qry where t.MyProperty.Contains(p, ' ') select t; } I also wrote an extension method public static bool Contains(this string str, IList<string> list, char seperator) { if (String.IsNullOrEmpty(str) || list == null) return false; var splitStr = str.Split(new char[] { seperator }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in splitStr) foreach (string l in list) if (String.Compare(s, l, true) == 0) return true; return false; } Any help or ideas on how I could achieve this?

    Read the article

  • LINQ to SQL: NOTing a prebuilt expression

    - by ck
    I'm building a library of functions for one of my core L2S classes, all of which return a bool to allow checking for certain situations. Example: Expression<Func<Account, bool>> IsSomethingX = a => a.AccountSupplementary != null && a.AccountSupplementary.SomethingXFlag != null && a.AccountSupplementary.SomethingXFlag.Value; Now to query where this is not true, I CAN'T do this: var myAccounts= context.Accounts .Where(!IsSomethingX); // does not compile However, using the syntax from the PredicateBuilder class, I've come up with this: public static IQueryable<T> WhereNot<T>(this IQueryable<T> items, Expression<Func<T, bool>> expr1) { var invokedExpr = Expression.Invoke(expr1, expr1.Parameters.Cast<Expression>()); return items.Where(Expression.Lambda<Func<T, bool>> (Expression.Not(invokedExpr), expr1.Parameters)); } var myAccounts= context.Accounts .WhereNot(IsSomethingX); // does compile which actually produces the correct SQL. Does this look like a good solution, and is there anything I need to be aware of that might cause me problems in future?

    Read the article

  • Creating a sort function for a generic list

    - by Andrey
    I have a method for sorting generic lists by the object fields: public static IQueryable<T> SortTable<T>(IQueryable<T> q, string sortfield, bool ascending) { var p = Expression.Parameter(typeof(T), "p"); if (typeof(T).GetProperty(sortfield).PropertyType == typeof(int?)) { var x = Expression.Lambda<Func<T, int?>>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } else if (typeof(T).GetProperty(sortfield).PropertyType == typeof(int)) { var x = Expression.Lambda<Func<T, int>>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } else if (typeof(T).GetProperty(sortfield).PropertyType == typeof(DateTime)) { var x = Expression.Lambda<Func<T, DateTime>>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } // many more for every type return q; } Is there any way I can collapse those ifs to a single generic statement? The main problem is that for the part Expression.Lambda<Func<T, int>> I am not sure how to write it generically.

    Read the article

  • Linq to SQL Intersect help needed

    - by mohang
    Hi, I have tried various suggestions given in SO. I still did not get the answers needed. Kindly help me. I appreciate your help. I have two sets. I need help to get the linq to sql intersection done. I have two sets. IQueryable<BusinessEntity> firstSet = from ent in all entities where ... // Code to get the first set. IQueryable<BusinessEntity> secondSet = from ent in all entities where... // Code to get the second set. Now I want the intersection, that is common elements of these sets. I have tried various ways including the following and I did not get the result I wanted. Please help me to get the right result. var commonEntities = (from ent1 in firstSet from ent2 in secondSet where ent1.BusinessEntityId == ent2.BusinessEntityId select ent1);

    Read the article

  • LinqtoSql Pre-compile Query problem with Count() on a group by

    - by Joe Pitz
    Have a LinqtoSql query that I now want to precompile. var unorderedc = from insp in sq.Inspections where insp.TestTimeStamp > dStartTime && insp.TestTimeStamp < dEndTime && insp.Model == "EP" && insp.TestResults != "P" group insp by new { insp.TestResults, insp.FailStep } into grp select new { FailedCount = (grp.Key.TestResults == "F" ? grp.Count() : 0), CancelCount = (grp.Key.TestResults == "C" ? grp.Count() : 0), grp.Key.TestResults, grp.Key.FailStep, PercentFailed = Convert.ToDecimal(1.0 * grp.Count() / tcount * 100) }; I have created this delegate: public static readonly Funct<SQLDataDataContext, int, string, string, DateTime, DateTime, IQueryable<CalcFailedTestResult>> GetInspData = CompiledQuery.Compile((SQLDataDataContext sq, int tcount, string strModel, string strTest, DateTime dStartTime, DateTime dEndTime, IQueryable<CalcFailedTestResult> CalcFailed) => from insp in sq.Inspections where insp.TestTimeStamp > dStartTime && insp.TestTimeStamp < dEndTime && insp.Model == strModel && insp.TestResults != strTest group insp by new { insp.TestResults, insp.FailStep } into grp select new { FailedCount = (grp.Key.TestResults == "F" ? grp.Count() : 0), CancelCount = (grp.Key.TestResults == "C" ? grp.Count() : 0), grp.Key.TestResults, grp.Key.FailStep, PercentFailed = Convert.ToDecimal(1.0 * grp.Count() / tcount * 100) }); The syntax error is on the CompileQuery.Compile() statement It appears to be related to the use of the select new {} syntax. In other pre-compiled queries I have written I have had to just use the select projection by it self. In this case I need to perform the grp.count() and the immediate if logic. I have searched SO and other references but cannot find the answer.

    Read the article

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