Search Results

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

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

  • Code to apply expression tree directly to List

    - by Gamma Vega
    Is there a method call in Linq that will apply a expression tree directly on a List<V>? For instance, if I have a expression tree that is built on Order type, and i have a collection of List<Order> items on which i need to apply this expression. I am looking something similar to: class OrderListStore : IQueryable<V>, <other interfaces required to implement custom linq provider> { List<Order> orders; public Expression Expression { get { return Expression.Constant(this); } } IEnumerator<V> IEnumerable<V>.GetEnumerator() { //Here I need to have a method that will take the existing expression //and directly apply on list something like this .. Expression.Translate(orders); } } Any help in this regard is highly appreciated.

    Read the article

  • Why is my ServiceOperation method missing from my WCF Data Services client proxy code?

    - by Kev
    I have a simple WCF Data Services service and I want to expose a Service Operation as follows: [System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class ConfigurationData : DataService<ProductRepository> { // This method is called only once to initialize service-wide policies. public static void InitializeService(IDataServiceConfiguration config) { config.SetEntitySetAccessRule("*", EntitySetRights.ReadMultiple | EntitySetRights.ReadSingle); config.SetServiceOperationAccessRule("*", ServiceOperationRights.All); config.UseVerboseErrors = true; } // This operation isn't getting generated client side [WebGet] public IQueryable<Product> GetProducts() { // Simple example for testing return (new ProductRepository()).Product; } Why isn't the GetProducts method visible when I add the service reference on the client?

    Read the article

  • Custom Logic and Proxy Classes in ADO.NET Data Services

    - by rasx
    I've just read "Injecting Custom Logic in ADO.NET Data Services" and my next question is, How do you get your [WebGet] method to show up in the client-side proxy classes? Sure, I can call this directly (RESTfully) with, say, WebClient but I thought the strong typing features in ADO.NET Data Services would "hide" this from me auto-magically. So here we have: public class MyService : DataService<MyDataSource> { // This method is called only once to initialize service-wide policies. public static void InitializeService(IDataServiceConfiguration config) { config.SetEntitySetAccessRule("Customers", EntitySetRights.AllRead); config.SetServiceOperationAccessRule("CustomersInCity", ServiceOperationRights.All); } [WebGet] public IQueryable<MyDataSource.Customers> CustomersInCity(string city) { return from c in this.CurrentDataSource.Customers where c.City == city select c; } } How can I get CustomersInCity() to show up in my client-side class defintions?

    Read the article

  • Help with linq to sql compiled query

    - by stackoverflowuser
    Hi I am trying to use compiled query for one of my linq to sql queries. This query contains 5 to 6 joins. I was able to create the compiled query but the issue I am facing is my query needs to check if the key is within a collection of keys passed as input. But compiled queries do not allow passing of collection (since collection can have varying number of items hence not allowed). For instance input to the function is a collection of keys. Say: List<Guid> InputKeys List<SomeClass> output = null; var compiledQuery = CompiledQueries.Compile<DataContext, IQueryable<SomeClass>>( (context) => from a in context.GetTable<A>() where InputKeys.Contains(a.Key) select a); using(var dataContext = new DataContext()) { output = compiledQuery(dataContext).ToList(); } return output; Is there any work around or better way to do the above?

    Read the article

  • Linq to Sql Projection Help

    - by Micah
    I've reached the end of my Linq rope. Need your help! Heres my table structure first(all linq to sql objects): InventoryItems -ID -AmtInStock IventoryKits -ID InventoryKits_to_InventoryItems -InventoryItemID -InventoryKitID So i need to do a projection like the following var q2=from k in GetAllKits()//returns IQueryable<InventoryKit> select new VMPublication()//ViewModel Object { ID = k.ID, Name = k.Name, WebAmountInStock = ,//need to get the Min() AmtInStock from InventoryItems here ItemCode = k.ItemCode, WebAmountOrdered = k.AmtOrdered.ToString(), WebReminderAmount = "", WebAmountWarning="", Type = "Kit" }; i have no idea how to get that Min() of InventoryItem's AmtInStock in that query. Please help! Very Appreciated!

    Read the article

  • NHibernate with or without Repository

    - by Groo
    There are several similar questions on this matter, by I still haven't found enough reasons to decide which way to go. The real question is, is it reasonable to abstract the NHibernate using a Repository pattern, or not? It seems that the only reason behind abstracting it is to leave yourself an option to replace NHibernate with a different ORM if needed. But creating repositories and abstracting queries seems like adding yet another layer, and doing much of the plumbing by hand. One option is to use expose IQueryable<T> to the business layer and use LINQ, but from my experience LINQ support is still not fully implemented in NHibernate (queries simply don't always work as expected, and I hate spending time on debugging a framework). Although referencing NHibernate in my business layer hurts my eyes, it is supposed to be an abstraction of data access by itself, right? What are you opinions on this?

    Read the article

  • Where to execute extra logic for linq to entities query?

    - by Inez
    Let say that I want to populate a list of CustomerViewModel which are built based on Customer Entity Framework model with some fields (like Balance) calculated separately. Below I have code which works for lists - it is implemented in my service layer, but also I want to execute this code when I just get one item from the database and execute is as well in different services where I'm accessing Customers data as well. How should I do this to ensure performance but to to not duplicate code - the one for calculating Balance? public List<CustomerViewModel> GetCustomerViewModelList() { IQueryable<CustomerViewModel> list = from k in _customerRepository.List() select new CustomerViewModel { Id = k.Id, Name = k.Name, Balance = k.Event.Where(z => z.EventType == (int) EventTypes.Income).Sum(z => z.Amount) }; return list.ToList(); }

    Read the article

  • Accessing Linq data in telerik grid ItemCreated method

    - by Jack
    Not sure if the title of this question makes sense, but here's my problem: I have a telerik grid bound to a Linq data object, however, I limit the fields returned: <IQueryable>filter = data.Select(x => new {x.ID, x.Name, x.Age}); I would like to access these fields in the ItemCreated method of the grid: protected void rgPeople_ItemCreated(object sender, GridItemEventArgs e) { Telerik.Web.UI.GridDataItem item = (GridDataItem)e.Item; ?????? Person = (???????)e.Item.DataItem; } What do I declare ?????? as so that I can use: String ID = Person.ID; String Name = Person.Name; etc

    Read the article

  • Unit Testing functions within repository interfaces - ASP.net MVC3 & Moq

    - by RawryLions
    I'm getting into writing unit testing and have implemented a nice repository pattern/moq to allow me to test my functions without using "real" data. So far so good.. However.. In my repository interface for "Posts" IPostRepository I have a function: Post getPostByID(int id); I want to be able to test this from my Test class but cannot work out how. So far I am using this pattern for my tests: [SetUp] public void Setup() { mock = new Mock<IPostRepository>(); } [Test] public void someTest() { populate(10); //This populates the mock with 10 fake entries //do test here } In my function "someTest" I want to be able to call/test the function GetPostById. I can find the function with mock.object.getpostbyid but the "object" is null. Any help would be appreciated :) iPostRepository: public interface IPostRepository { IQueryable<Post> Posts {get;} void SavePost(Post post); Post getPostByID(int id); }

    Read the article

  • linq expression in vb.net

    - by Thurein
    Hi, Can any body translate the following c# code to vb. I have tried telarik code converter but I got problem at expression.call and it won't compile at all. private static IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName, bool descending, bool anotherLevel) { ParameterExpression param = Expression.Parameter(typeof(T), string.Empty); MemberExpression property = Expression.PropertyOrField(param, propertyName); LambdaExpression sort = Expression.Lambda(property, param); MethodCallExpression call = Expression.Call( typeof(Queryable), (!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : string.Empty), new[] { typeof(T), property.Type }, // error line source.Expression, Expression.Quote(sort)); return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call); } thanks Thurein

    Read the article

  • Linq to Sql, Repositories, and Asp.Net MVC ViewData: How to remove redundancy?

    - by Dr. Zim
    Linq to SQL creates objects which are IQueryable and full of relations. Html Helpers require specific interface objects like IEnumerable<SelectListItem>. What I think could happen: Reuse the objects from Linq to SQL without all the baggage, i.e., return Pocos from the Linq to SQL objects without additional Domain Model classes? Extract objects that easily convert to (or are) Html helper objects like the SelectListItem enumeration? Is there any way to do this without breaking separation of concerns? Some neat oop trick to bridge the needs? For example, if this were within a repository, the SelectListItem wouldn't be there. The select new is a nice way to cut out an object from the Linq to SQL without the baggage but it's still referencing a class that shouldn't be referenced: IEnumerable<SelectListItem> result = (from record in db.table select new SelectListItem { Selected = record.selected, Text= record.Text, Value= record.Value } ).AsEnumerable();

    Read the article

  • Linq to Entities, checking for specific foreign key id?

    - by AaronLS
    I am trying to get rows where the foreign key ParentID == 0, and this is what I am trying but I get a NotSupportedException because it can't translate the ArrayIndex [0]: IQueryable<ApplicationSectionNode> topLevelNodeQuery = from n in uacEntitiesContext.ApplicationSectionNodeSet where (int)n.Parent.EntityKey.EntityKeyValues[0].Value == 0 orderby n.Sequence select n; So I need to pull that ArrayIndex out of the query so that the runtime can successfully translate the query. I'm not sure how to do that though. How does one query a specific object via it's primary key or set of objects via foreign key? Edit: Note that there is not actually a row in the table with NodeId == 0, the 0 is a magic value(not my idea) to indicate top level nodes. So I can't do n.Parent.NodeId == 0

    Read the article

  • Linq to SQL gives NotSupportedException when using local variables

    - by zwanz0r
    It appears to me that it matters whether you use a variable to temporary store an IQueryable or not. See the simplified example below: This works: List<string> jobNames = new List<string> { "ICT" }; var ictPeops = from p in dataContext.Persons where ( from j in dataContext.Jobs where jobNames.Contains(j.Name) select j.ID).Contains(p.JobID) select p; But when I use a variable to temporary store the subquery I get an exception: List<string> jobNames = new List<string> { "ICT" }; var jobs = from j in dataContext.Jobs where jobNames.Contains(j.Name) select j.ID; var ictPeops = from p in dataContext.Persons where jobs.Contains(p.JobID) select p; "System.NotSupportedException: Queries with local collections are not supported" I don't see what the problem is. Isn't this logic that is supposed to work in LINQ?

    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

  • Cannot Translate to SQL using Select(x => Func(x))

    - by Dan
    I'm slowly learning the ins and outs of LINQtoSQL, but this is confusing me. Here is the statement I have: IQueryable<IEvent> events = (from e in db.getEvents() select e).Select(x => SelectEvent(x, null)); What the SelectEvent does can be explained in this answer here. I am not using the .toList() function as I don't want potentially thousands of records brought into memory. public IEvent SelectEvent(SqlServer.Event ev, EventType? type) { // Create an object which implements IEvent // I don't have the code in front of me, so forgive the lack of code } My question is really for the Select() method. I get the "Cannot translate to SQL" error and the Select() is listed in the error message. Clueless on this one :-/.

    Read the article

  • Create LINQ to entities OrderBy expression on the fly

    - by AyKarsi
    I'm trying to add the orderby expression on the fly. But when the query below is executed I get the following exception: System.NotSupportedException: Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context. The strange thing is, I am query exactly those primitive types only. string sortBy = HttpContext.Current.Request.QueryString["sidx"]; ParameterExpression prm = Expression.Parameter(typeof(buskerPosting), "posting"); Expression orderByProperty = Expression.Property(prm, sortBy); // get the paged records IQueryable<PostingListItemDto> query = (from posting in be.buskerPosting where posting.buskerAccount.cmsMember.nodeId == m.Id orderby orderByProperty //orderby posting.Created select new PostingListItemDto { Set = posting }).Skip<PostingListItemDto>((page - 1) * pageSize).Take<PostingListItemDto>(pageSize); Hope somebody can shed some light on this!

    Read the article

  • EF4: common interface for EF entities

    - by Feryt
    Hi. I have public interface: public interface IEntity { int ID { get; set; } string Name { get; set; } bool IsEnabled { get; set; } } ehich some EF entities implements(thanks to partial class) and extesion method: public static IEnumerable<SelectListItem> ToSelectListItems<T>(this IQueryable<T> entities, int? selectedID = null) where T : IEntity { return entities.Select(c => new { c.Name, c.ID }).ToList().Select(c => new SelectListItem { Text = c.Name, Value = c.ID.ToString(), Selected = (c.ID == selectedID) }); } Calling ToSelectListItems return exception: Unable to cast the type '<EF entity name>' to type 'IEntity'. LINQ to Entities only supports casting Entity Data Model primitive types. Why, any ideas? Thank you.

    Read the article

  • Json return code to simplify if possible.

    - by pirzada
    Can you simplify this code?. Is there anything we can do to make it more simple. I am not sure but it looks ugly to me. [HttpPost] public JsonResult UserDetailById(int userId, string username) { IQueryable<Company> repository = companyRepository.GetGridCompanies(); Employee emp = companyRepository.GetEmployee(userId); //Drop down fill var a = (from c in repository .OrderBy(c => c.companyName) select new { Id = c.companyID, Name = c.companyName }).ToArray(); var data = new { Id = emp.companyID.ToString(), Name = emp.employeeFirstname + " " + emp.employeeLastname, Fn = emp.employeeFirstname, Ln = emp.employeeLastname, Dept = emp.employeeDepartment, Sup = emp.employeeSup.ToString(), HireDate = String.Format("{0:MM/dd/yyyy}", emp.employeeHiredate), CompVm = a }; return Json(data); }

    Read the article

  • Does this code describe an Existential Type in C#?

    - by noblethrasher
    Currently watching Bart De Smet's explanation of IQueryable and he mentioned Existential Types (which I've been curious about for some time). After reading the answers to this question I'm just wondering if this is a way to construct it in C#: public abstract class ExistentialType { private ExistentialType() { } public abstract int Foo(); public ExistentialType Create() { return new ConcreateType1(); } private class ConcreateType1 : ExistentialType { public override int Foo() { throw new NotImplementedException(); } } private class ConcreateType2 : ExistentialType { public override int Foo() { throw new NotImplementedException(); } } private class ConcreateType3 : ExistentialType { public override int Foo() { throw new NotImplementedException(); } } }

    Read the article

  • System.Linq.Dynamic and DateTime

    - by Matthew Hood
    I am using System.Linq.Dynamic to do custom where clauses from an ajax call in .Net MVC 1.0. It works fine for strings, int etc but not for DateTime, I get the exception cannot compare String to DateTime. The very simple test code is items = items.Where(string.Format(@" {0} {1}{2}{1} ", searchField, delimiter, searchString)); Where searchField will be for example start_date and the data type is DateTime, delimiter is " (tried with nothing as well) and searchString will be 01-Jan-2009 (tried with 01/01/2009 as well) and items is an IQueryable from LinqToSql. Is there a way of specifying the data type in a dynamic where, or is there a better approach. It is currently already using some reflection to work out what type of delimiter is required.

    Read the article

  • How do I make this Query against EF Efficient?

    - by dudeNumber4
    Using EF4. Assume I have this: IQueryable<ParentEntity> qry = myRepository.GetParentEntities(); Int32 n = 1; What I want to do is this, but EF can't compare against null. qry.Where( parent => parent.Children.Where( child => child.IntCol == n ) != null ) What works is this, but the SQL it produces (as you would imagine) is pretty inefficient: qry.Where( parent => parent.Children.Where( child => child.IntCol == n ).FirstOrDefault().IntCol == n ) How can I do something like the first comparison to null that won't be generating nested queries and so forth?

    Read the article

  • Compiled query using list of class objects in C#

    - by Sukan
    Hello , Can somebody help me out in creating compiled queries where input is to be a list of class objects? I have seen examples where Func<DataContext, somematchobject, IQueryable<T>> is created and compiled. But can I do something like Func<List<T>, matchObject, T>, and compile it? Basically I want an object(T) meeting certain conditions (as in matchObject) to be returned from a list of objects(List<T>). Will CompiledQuery.Compile help me in this? Please help me experts!!

    Read the article

  • How can I do this Aggrigate, group by, in query in LINQ?

    - by Ólafur Waage
    Please do not give me a full working example, I want to know how this is done rather than to get some code I can copy paste This is the query I need, and can't for the life of me create it in LINQ. SELECT * FROM dbo.Schedules s, dbo.Videos v WHERE s.VideoID = v.ID AND s.ID IN ( SELECT MAX(ID) FROM dbo.Schedules WHERE ChannelID = 1 GROUP BY VideoID ) ORDER BY v.Rating DESC, s.StartTime DESC I have the "IN" query in LINQ I think, it's something like this var uniqueList = from schedule in db.Schedules where schedule.ChannelID == channelID group schedule by schedule.VideoID into s select new { id = s.Max(i => i.ID) }; It is possibly wrong, but now I can not check in another query for this in a where clause uniqueList.Contains(schedule.ID) There is possibly a better way to write this query, if you have any idea I would love some hints. I get this error and it's not making much sense. The type arguments for method 'System.Linq.Queryable.Contains(System.Linq.IQueryable, TSource)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

    Read the article

  • Help with Linq and Generics

    - by Jonathan
    Hi to all. I'm triying to make a function that add a 'where' clause to a query based in a property and a value. This is a very simplefied version of my function. Private Function simplified(ByVal query As IQueryable(Of T), ByVal PValue As Long, ByVal p As PropertyInfo) As ObjectQuery(Of T) query = query.Where(Function(c) DirectCast(p.GetValue(c, Nothing), Long) = PValue) Dim t = query.ToList 'this line is only for testing, and here is the error raise Return query End Function The error message is: LINQ to Entities does not recognize the method 'System.Object CompareObjectEqual(System.Object, System.Object, Boolean)' method, and this method cannot be translated into a store expression. Looks like a can't use GetValue inside a linq query. Can I achieve this in other way? Post your answer in C#/VB. Chose the one that make you feel more confortable. Thanks

    Read the article

  • How to use LINQ to SQL to create ranked search results?

    - by quakkels
    I am looking for a way to use l2s to return ranked result based on keywords. I would like to take a keyword and be able to search the table for that keyword using .contains(). The trick that I haven't been able to figure out is how to get a count of how many times that keyqord appears, and then .OrderByDescending() based on that count. So if i had some thing like: string keyword = "SomeKeyword"; IQueryable<Article> searchResults = from a in GenesisRepository.Article where a.Body.Contains(keyword) select a; What is the best way to order searchResults based on the number of times keyword appears in a.Body? Thanks for any help.

    Read the article

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