Search Results

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

Page 3/18 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Type or namespace name could not be found

    - by Pandiya Chendur
    I use this: public IQueryable<MaterialsView> FindAllMaterials() { var materials = from m in db.Materials join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id select new MaterialsView { MatId = m.Mat_Name, MesName = Mt.Name, MesType = m.Mat_Type }; return materials; } It gives me the following errors: The type or namespace name MaterialsView could not be found (are you missing a using directive or an assembly reference?) Cannot implicitly convert type System.Collections.Generic.IEnumerable<MaterialsView> to System.Linq.IQueryable<MaterialsView>. An explicit conversion exists (are you missing a cast?) The type arguments for method System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>) cannot be inferred from the usage. Try specifying the type arguments explicitly. I have googled it and found this SO question but it doesn't help. What's wrong?

    Read the article

  • I need to convert the result of a stored procedure in a dbml file to IQueryable to view a list in an

    - by RJ
    I have a MVC project that has a Linq to SQL dbml class. It is a table called Clients that houses client information. I can easily get the information to display in a View using the code I followed in Nerd Dinner but I have added a stored procedure to the dbml and it's result set is of IQueryable, not IQueryable. I need to convert IQueryable to IQueryable so I can display it in the same View. The reason for the sproc is so I can pass a search string tothe sproc and return the same information as a full list but filtered on the search. I know I can use Linq to filter the whole list but I don't want the whole list so I am using the sproc. Here is the code in my ClientRepository with a comment where I need to convert. What code goes in the commented spot. public IQueryable<Client> SelectClientsBySearch(String search) { IQueryable<SelectClientsBySearchResult> spClientList = (from p in db.SelectClientsBySearch(search) select p).AsQueryable(); //what is the code to convert IQueryable<SelectClientsBySearchResult> to IQueryable<Client> return clientList; }

    Read the article

  • how VAR is determined against many options?

    - by Royi Namir
    i have this code : IEnumerable<string> q = customers /*EF entity*/ .Select (c => c.Name.ToUpper()) .OrderBy (n => n) To select entity, ObjectContext actually create ObjectQuery, which implement IQueryable. The object return from ObjectQuery, is not normal object, but EntityObject but what if i write : ( notice the var) var q = customers /*EF entity*/ .Select (c => c.Name.ToUpper()) .OrderBy (n => n) it can be determined both to ienumerable or iqueryable : because ObjectQuery Also implements IEnumerable... i dont know if there's any specific info which tell the compiler "use A and not B. A is more specific..." ( there must be...i just cant find it) any help ? how will it know to use A || B ?

    Read the article

  • Making linq avoid using in memory filtering where possible

    - by linqmonkey
    Consider the these two LINQ2SQL data retrieval methods. The first creates a 'proper' SQL statement that filters the data, but requires passing the data context into the method. The second has a nicer syntax but loads the entire list of that accounts projects, then does in memory filtering. Is there any way to preserve the syntax of the second method but with the performance advantage of the first? public partial class Account { public IQueryable<Project> GetProjectsByYear(LinqDataContext context, int year) { return context.Projects.Where(p => p.AccountID==this.AccountID && p.Year==year).OrderBy(p => p.ProjectNo) } public IQueryable<Project> GetProjectsByYear(int year) { return this.Projects.Where(p => p.Year==year).OrderBy(p => p.ProjectNo).AsQueryable() } }

    Read the article

  • What to put as the Provider for a mocked IQueryable

    - by Vaccano
    I am working with Moles and mocking a System.Data.Linq.Table. I got it constructing fine, but when I use it, it wants IQueryable.Provider to be mocked (moled) as well. I just want it to use normal Linq To Objects. Any idea what that would be? Here is the syntax I can use: MTable<User> userTable = new System.Data.Linq.Moles.MTable<User>(); userTable.Bind(new List<User> { UserObjectHelper.TestUser() }); // this is the line that needs help MolesDelegates.Func<IQueryProvider> provider = //Insert provider here! ^ userTable.ProviderSystemLinqIQueryableget = provider | | | what can I put here? ----------------------------------------+

    Read the article

  • Linq IQueryable variables

    - by kevinw
    Hi i have a function that should return me a string but what is is doing is bringing me back the sql expression that i am using on the database what have i done wrong public static IQueryable XMLtoProcess(string strConnection) { Datalayer.HameserveDataContext db = new HameserveDataContext(strConnection); var xml = from x in db.JobImports where x.Processed == false select new { x.Content }; return xml; } this is the code sample this is what i should be getting back <PMZEDITRI TRI_TXNNO="11127" TRI_TXNSEQ="1" TRI_CODE="600" TRI_SUBTYPE="1" TRI_STATUS="Busy" TRI_CRDATE="2008-02-25T00:00:00.0000000-00:00" TRI_CRTIME="54540" TRI_PRTIME="0" TRI_BATCH="" TRI_REF="" TRI_CPY="main" C1="DEPL" C2="007311856/001" C3="14:55" C4="CUB2201" C5="MR WILLIAM HOGG" C6="CS12085393" C7="CS" C8="Blocked drain" C9="Scheme: CIS Home Rescue edi tests" C10="MR WILLIAM HOGG" C11="74 CROMARTY" C12="OUSTON" C13="CHESTER LE STREET" C14="COUNTY DURHAM" C15="" C16="DH2 1JY" C17="" C18="" C19="" C20="" C21="CIS" C22="0018586965 ||" C23="BD" C24="W/DE/BD" C25="EX-DIRECTORY" C26="" C27="/" C28="CIS Home Rescue" C29="CIS Home Rescue Plus Insd" C30="Homeserve Claims Management Ltd|Upon successful completion of this repair the contractor must submit an itemised and costed Homeserve Claims Management Ltd Job Sheet." N1="79.9000" N2="68.0000" N3="11.9000" N4="0" N5="0" N6="0" D1="2008-02-25T00:00:00.0000000-00:00" T2="EX-DIRECTORY" T4="Blocked drain" TRI_SYSID="9" TRI_RETRY="3" TRI_RETRYTIME="0" /> can anyone help me please

    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

  • C# Select clause returns system exception instead of relevant object

    - by Kashif
    I am trying to use the select clause to pick out an object which matches a specified name field from a database query as follows: objectQuery = from obj in objectList where obj.Equals(objectName) select obj; In the results view of my query, I get: base {System.SystemException} = {"Boolean Equals(System.Object)"} Where I should be expecting something like a Car, Make, or Model Would someone please explain what I am doing wrong here? The method in question can be seen here: // this function searches the database's table for a single object that matches the 'Name' property with 'objectName' public static T Read<T>(string objectName) where T : IEquatable<T> { using (ISession session = NHibernateHelper.OpenSession()) { IQueryable<T> objectList = session.Query<T>(); // pull (query) all the objects from the table in the database int count = objectList.Count(); // return the number of objects in the table // alternative: int count = makeList.Count<T>(); IQueryable<T> objectQuery = null; // create a reference for our queryable list of objects T foundObject = default(T); // create an object reference for our found object if (count > 0) { // give me all objects that have a name that matches 'objectName' and store them in 'objectQuery' objectQuery = from obj in objectList where obj.Equals(objectName) select obj; // make sure that 'objectQuery' has only one object in it try { foundObject = (T)objectQuery.Single(); } catch { return default(T); } // output some information to the console (output screen) Console.WriteLine("Read Make: " + foundObject.ToString()); } // pass the reference of the found object on to whoever asked for it return foundObject; } } Note that I am using the interface "IQuatable<T>" in my method descriptor. An example of the classes I am trying to pull from the database is: public class Make: IEquatable<Make> { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual IList<Model> Models { get; set; } public Make() { // this public no-argument constructor is required for NHibernate } public Make(string makeName) { this.Name = makeName; } public override string ToString() { return Name; } // Implementation of IEquatable<T> interface public virtual bool Equals(Make make) { if (this.Id == make.Id) { return true; } else { return false; } } // Implementation of IEquatable<T> interface public virtual bool Equals(String name) { if (this.Name.Equals(name)) { return true; } else { return false; } } } And the interface is described simply as: public interface IEquatable<T> { bool Equals(T obj); }

    Read the article

  • LINQ DataLoadOptions - Retrieval of data via Fulltext/Broken Foreign Key Relationship

    - by Alex
    I've hit a brick wall: I have an SQL Function: FUNCTION [dbo].[ContactsFTS] (@searchtext nvarchar(4000)) RETURNS TABLE AS RETURN SELECT * FROM Contacts INNER JOIN CONTAINSTABLE(Contacts, *, @searchtext) AS KEY_TBL ON Contacts.Id = KEY_TBL.[KEY] which I am calling via LINQ public IQueryable<ContactsFTSResult> SearchByFullText(String searchText) { return db.ContactsFTS(searchText); } I am projecting the ContactsFTSResult collection into a List<Contact> which is then given to my viewmodel. Here is the problem: My Contacts table (and therefore the Contact object created via LINQ to SQL) has multiple FK relationships to other information, such as Contact.BillingAddressId is an FK to an Address.Id. That information is missing after I do the fulltext search (e.g. if I try to access Contact.BillingAddress it is null). Can I add this information somehow via DataLoadOptions? I tried LoadWith<Contact>(c => c.BillingAddress) but this doesn't work, I assume because of the fact that I'm calling the function instead of doing the whole query via LINQ.

    Read the article

  • How to define a collection in a POCO in Entity Framework 4?

    - by Stef
    Lets say I've a Team class which contains 0 or more Players. The Player class is easy: public class Player { public long Id { get; set; } public string Name { get; set; } public Team Team { get; set; } } But whats the best to define the Team class? Option 1 public class Team { public long Id { get; set; } public string Name { get; set; } public ICollection<Player> Players { get; set; } } Option 2: public class Team { public Team() { Players = new Collection<Player>(); } public long Id { get; set; } public string Name { get; set; } public ICollection<Player> Players { get; set; } } Option 3: public class Team { public long Id { get; set; } public string Name { get; set; } public IQueryable<Player> Players { get; set; } } Option 4: public class Team { public long Id { get; set; } public string Name { get; set; } public ObjectSet<Player> Players { get; set; } }

    Read the article

  • Can't get results from a IQueryable.

    - by StackPointer
    Hi! I have the following code in Linq to Entity: var policy= from pol in conn.Policy where pol.Product.DESCRIPTION=="someProduct" SELECT pol; Then, the table Policy, has some dependencies for a table called Entity. If I do this: foreach(Policy p in policy){ if(!p.Entity.IsLoaded) p.Entity.Load(); IEnumerable<Entity> entities= from ent in p.Entity Where ent.EntityType.DESCRIPTION=="SomeEntityType" select ent; Console.Writeline(entities.ElementAt(0).NAME); } It says, "Object not set to an instance", but if I do: foreach(Policy p in policy){ if(!p.Entity.IsLoaded) p.Entity.Load(); foreach(Entity et in p.Entity)Console.Write(et.NAME); } It works! Can anyone tell me why? Thank you, Best regards.

    Read the article

  • how to rotate around each record in linq and show that in view

    - by Sadegh
    Hi, I have four tables in my database and i want to join that's and return record's and show that into searchController! My query is this: public IQueryable PerformSearch(string query) { if (!string.IsNullOrEmpty(query)) { var results = from tbl1 in context.Table1 join tbl2 in context.Table2 on tbl1.Id equals tbl2.Id join tbl3 in context.Table3 on tbl2.Id equals tbl3.Id join tbl4 in context.Table4 on tbl3.Id equals tbl4.Id where tbl1.col2.Contains(query) orderby tbl1.Count descending select new { col1 = tbl1.Col1, col1 = tbl1.Col1, col1 = tbl1.Col1, . . . }; return results.AsQueryable(); } else return null; } And this method called in SearchController as below: public class SearchController : System.Web.Mvc.Controller { public System.Web.Mvc.ActionResult Search(System.String query) { var search = new Search(); ViewData["result"] = search.PerformSearch(query); return View("Search"); } } I don't know how i can rotate around each record (plus vs intellisense feature) returned by PeformSeach method and show that in view! Also is this a good way? thanks in advance

    Read the article

  • How do I add a where filter using the original Linq-to-SQL object in the following scenario

    - by GenericTypeTea
    I am performing a select query using the following Linq expression: Table<Tbl_Movement> movements = context.Tbl_Movement; var query = from m in movements select new MovementSummary { Id = m.DocketId, Created = m.DateTimeStamp, CreatedBy = m.Tbl_User.FullName, DocketNumber = m.DocketNumber, DocketTypeDescription = m.Ref_DocketType.DocketType, DocketTypeId = m.DocketTypeId, Site = new Site() { Id = m.Tbl_Site.SiteId, FirstLine = m.Tbl_Site.FirstLine, Postcode = m.Tbl_Site.Postcode, SiteName = m.Tbl_Site.SiteName, TownCity = m.Tbl_Site.TownCity, Brewery = new Brewery() { Id = m.Tbl_Site.Ref_Brewery.BreweryId, BreweryName = m.Tbl_Site.Ref_Brewery.BreweryName }, Region = new Region() { Description = m.Tbl_Site.Ref_Region.Description, Id = m.Tbl_Site.Ref_Region.RegionId } } }; I am also passing in an IFilter class into the method where this select is performed. public interface IJobFilter { int? PersonId { get; set; } int? RegionId { get; set; } int? SiteId { get; set; } int? AssetId { get; set; } } How do I add these where parameters into my SQL expression? Preferably I'd like this done in another method as the filtering will be re-used across multiple repositories. Unfortunately when I do query.Where it has become an IQueryable<MovementSummary>. I'm assuming it has become this as I'm returning an IEnumerable<MovementSummary>. I've only just started learning LINQ, so be gentle.

    Read the article

  • Adding LambaExpression to an instance of IQueryable

    - by Paul Knopf
    ParameterExpression parameter = Expression.Parameter(typeof(Product), "x"); MemberExpression Left = Expression.MakeMemberAccess(parameter, typeof(Product).GetProperty("Name")); ConstantExpression Right = Expression.Constant(value, typeof(String)); BinaryExpression expression = Expression.Equal(Left, Right); LambdaExpression lambada = Expression.Lambda<Func<Product, bool>>(expression, parameter); Now how do I add this lambada to an instance of an IQuerybale, lets say _query _query.Where(lambada.Compile());?

    Read the article

  • Efficient way to call .Sum() on multiple properties

    - by SherCoder
    I have a function that uses Linq to get data from the database and then I call that function in another function to sum all the individual properties using .Sum on each individual property. I was wondering if there is an efficient way to sum all the properties at once rather than calling .Sum() on each individual property. I think the way I am doing as of right now, is very slow (although untested). public OminitureStats GetAvgOmnitureData(int? fnsId, int dateRange) { IQueryable<OminitureStats> query = GetOmnitureDataAsQueryable(fnsId, dateRange); int pageViews = query.Sum(q => q.PageViews); int monthlyUniqueVisitors = query.Sum(q => q.MonthlyUniqueVisitors); int visits = query.Sum(q => q.Visits); double pagesPerVisit = (double)query.Sum(q => q.PagesPerVisit); double bounceRate = (double)query.Sum(q => q.BounceRate); return new OminitureStats(pageViews, monthlyUniqueVisitors, visits, bounceRate, pagesPerVisit); }

    Read the article

  • Linq based generic alternate to Predicate<T>?

    - by Eric
    I have an interface called ICatalog as shown below where each ICatalog has a name and a method that will return items based on a Predicate<Item> function. public interface ICatalog { string Name { get; } IEnumerable<IFamily> GetItems(Predicate<Item> predicate); } A specific implementation of a catalog may be linked to catalogs in various format such as XML, or a SQL database. With an XML catalog I end up deserializing the entire XML file into memory, so testing each item with the predicate function does does not add a whole lot more overhead as it's already in memory. Yet with the SQL implementation I'd rather not retrieve the entire contents of the database into memory, and then filter the items with the predicate function. Instead I'd want to find a way to somehow pass the predicate to the SQL server, or somehow convert it to a SQL query. This seems like a problem that can be solved with Linq, but I'm pretty new to it. Should my interface return IQueryable instead?

    Read the article

  • Normalizing chains of .Skip() and .Take() calls

    - by dtb
    I'm trying to normalize arbitrary chains of .Skip() and .Take() calls to a single .Skip() call followed by an optional single .Take() call. Here are some examples of expected results, but I'm not sure if these are correct: .Skip(5) => .Skip(5) .Take(7) => .Skip(0).Take(7) .Skip(5).Skip(7) => .Skip(12) .Skip(5).Take(7) => .Skip(5).Take(7) .Take(7).Skip(5) => .Skip(5).Take(2) .Take(5).Take(7) => .Skip(0).Take(5) .Skip(5).Skip(7).Skip(11) => .Skip(23) .Skip(5).Skip(7).Take(11) => .Skip(12).Take(11) .Skip(5).Take(7).Skip(3) => .Skip(8).Take(4) .Skip(5).Take(7).Take(3) => .Skip(5).Take(4) .Take(11).Skip(5).Skip(3) => .Skip(8).Take(3) .Take(11).Skip(5).Take(7) => .Skip(5).Take(6) .Take(11).Take(5).Skip(3) => .Skip(3).Take(2) .Take(11).Take(5).Take(3) => .Skip(0).Take(3) Can anyone confirm these are the correct results to be expected? Here is the basic algorithm that I derived from the examples: class Foo { private int skip; private int? take; public Foo Skip(int value) { if (value < 0) value = 0; this.skip += value; if (this.take.HasValue) this.take -= value; return this; } public Foo Take(int value) { if (value < 0) value = 0; if (!this.take.HasValue || value < this.take) this.take = value; return this; } } Any idea how I can confirm if this is the correct algorithm?

    Read the article

  • Linq to NHibernate using Queryable.Where predicate

    - by Groo
    I am querying an SQLite database using LINQ to NHibernate. Person is an entity containing an Id and a Name: public class Person { public Guid Id { get; private set; } public string Name { get; private set; } } Let's say my db table contains a single person whose name is "John". This test works as expected: var query = from item in session.Linq<Person>() where (item.Name == "Mike") select item; // no such entity should exist Assert.IsFalse(query.Any()); but this one fails: var query = from item in session.Linq<Person>() select item; query.Where(item => item.Name == "Mike"); // following line actually returns the // "John" entry Assert.IsFalse(query.Any()); What am I missing?

    Read the article

  • EF Query with conditional include that uses Joins

    - by makerofthings7
    This is a follow up to another user's question. I have 5 tables CompanyDetail CompanyContacts FK to CompanyDetail CompanyContactsSecurity FK to CompanyContact UserDetail UserGroupMembership FK to UserDetail How do I return all companies and include the contacts in the same query? I would like to include companies that contain zero contacts. Companies have a 1 to many association to Contacts, however not every user is permitted to see every Contact. My goal is to get a list of every Company regardless of the count of Contacts, but include contact data. Right now I have this working query: var userGroupsQueryable = _entities.UserGroupMembership .Where(ug => ug.UserID == UserID) .Select(a => a.GroupMembership); var contactsGroupsQueryable = _entities.CompanyContactsSecurity;//.Where(c => c.CompanyID == companyID); /// OLD Query that shows permitted contacts /// ... I want to "use this query inside "listOfCompany" /// //var permittedContacts= from c in userGroupsQueryable //join p in contactsGroupsQueryable on c equals p.GroupID //select p; However this is inefficient when I need to get all contacts for all companies, since I use a For..Each loop and query each company individually and update my viewmodel. Question: How do I shoehorn the permittedContacts variable above and insert that into this query: var listOfCompany = from company in _entities.CompanyDetail.Include("CompanyContacts").Include("CompanyContactsSecurity") where company.CompanyContacts.Any( // Insert Query here.... // b => b.CompanyContactsSecurity.Join(/*inner*/,/*OuterKey*/,/*innerKey*/,/*ResultSelector*/) ) select company; My attempt at doing this resulted in: var listOfCompany = from company in _entities.CompanyDetail.Include("CompanyContacts").Include("CompanyContactsSecurity") where company.CompanyContacts.Any( // This is concept only... doesn't work... from grps in userGroupsQueryable join p in company.CompanyContactsSecurity on grps equals p.GroupID select p ) select company;

    Read the article

  • Creating an ASP.NET report using Visual Studio 2010 - Part 1

    - by rajbk
    This tutorial walks you through creating an report based on the Northwind sample database. You will add a client report definition file (RDLC), create a dataset for the RDLC, define queries using LINQ to Entities, design the report and add a ReportViewer web control to render the report in a ASP.NET web page. The report will have a chart control. Different results will be generated by changing filter criteria. At the end of the walkthrough, you should have a UI like the following.  From the UI below, a user is able to view the product list and can see a chart with the sum of Unit price for a given category. They can filter by Category and Supplier. The drop downs will auto post back when the selection is changed.  This demo uses Visual Studio 2010 RTM. This post is split into three parts. The last part has the sample code attached. Creating an ASP.NET report using Visual Studio 2010 - Part 2 Creating an ASP.NET report using Visual Studio 2010 - Part 3   Lets start by creating a new ASP.NET empty web application called “NorthwindReports” Creating the Data Access Layer (DAL) Add a web form called index.aspx to the root directory. You do this by right clicking on the NorthwindReports web project and selecting “Add item..” . Create a folder called “DAL”. We will store all our data access methods and any data transfer objects in here.   Right click on the DAL folder and add a ADO.NET Entity data model called Northwind. Select “Generate from database” and click Next. Create a connection to your database containing the Northwind sample database and click Next.   From the table list, select Categories, Products and Suppliers and click next. Our Entity data model gets created and looks like this:    Adding data transfer objects Right click on the DAL folder and add a ProductViewModel. Add the following code. This class contains properties we need to render our report. public class ProductViewModel { public int? ProductID { get; set; } public string ProductName { get; set; } public System.Nullable<decimal> UnitPrice { get; set; } public string CategoryName { get; set; } public int? CategoryID { get; set; } public int? SupplierID { get; set; } public bool Discontinued { get; set; } } Add a SupplierViewModel class. This will be used to render the supplier DropDownlist. public class SupplierViewModel { public string CompanyName { get; set; } public int SupplierID { get; set; } } Add a CategoryViewModel class. public class CategoryViewModel { public string CategoryName { get; set; } public int CategoryID { get; set; } } Create an IProductRepository interface. This will contain the signatures of all the methods we need when accessing the entity model.  This step is not needed but follows the repository pattern. interface IProductRepository { IQueryable<Product> GetProducts(); IQueryable<ProductViewModel> GetProductsProjected(int? supplierID, int? categoryID); IQueryable<SupplierViewModel> GetSuppliers(); IQueryable<CategoryViewModel> GetCategories(); } Create a ProductRepository class that implements the IProductReposity above. The methods available in this class are as follows: GetProducts – returns an IQueryable of all products. GetProductsProjected – returns an IQueryable of ProductViewModel. The method filters all the products based on SupplierId and CategoryId if any. It then projects the result into the ProductViewModel. GetSuppliers() – returns an IQueryable of all suppliers projected into a SupplierViewModel GetCategories() – returns an IQueryable of all categories projected into a CategoryViewModel  public class ProductRepository : IProductRepository { /// <summary> /// IQueryable of all Products /// </summary> /// <returns></returns> public IQueryable<Product> GetProducts() { var dataContext = new NorthwindEntities(); var products = from p in dataContext.Products select p; return products; }   /// <summary> /// IQueryable of Projects projected /// into the ProductViewModel class /// </summary> /// <returns></returns> public IQueryable<ProductViewModel> GetProductsProjected(int? supplierID, int? categoryID) { var projectedProducts = from p in GetProducts() select new ProductViewModel { ProductID = p.ProductID, ProductName = p.ProductName, UnitPrice = p.UnitPrice, CategoryName = p.Category.CategoryName, CategoryID = p.CategoryID, SupplierID = p.SupplierID, Discontinued = p.Discontinued }; // Filter on SupplierID if (supplierID.HasValue) { projectedProducts = projectedProducts.Where(a => a.SupplierID == supplierID); }   // Filter on CategoryID if (categoryID.HasValue) { projectedProducts = projectedProducts.Where(a => a.CategoryID == categoryID); }   return projectedProducts; }     public IQueryable<SupplierViewModel> GetSuppliers() { var dataContext = new NorthwindEntities(); var suppliers = from s in dataContext.Suppliers select new SupplierViewModel { SupplierID = s.SupplierID, CompanyName = s.CompanyName }; return suppliers; }   public IQueryable<CategoryViewModel> GetCategories() { var dataContext = new NorthwindEntities(); var categories = from c in dataContext.Categories select new CategoryViewModel { CategoryID = c.CategoryID, CategoryName = c.CategoryName }; return categories; } } Your solution explorer should look like the following. Build your project and make sure you don’t get any errors. In the next part, we will see how to create the client report definition file using the Report Wizard.   Creating an ASP.NET report using Visual Studio 2010 - Part 2

    Read the article

  • Is there anything wrong with having a few private methods exposing IQueryable<T> and all public meth

    - by Nate Bross
    I'm wondering if there is a better way to approach this problem. The objective is to reuse code. Let’s say that I have a Linq-To-SQL datacontext and I've written a "repository style" class that wraps up a lot of the methods I need and exposes IQueryables. (so far, no problem). Now, I'm building a service layer to sit on top of this repository, many of the service methods will be 1<-1 with repository methods, but some will not. I think a code sample will illustrate this better than words. public class ServiceLayer { MyClassDataContext context; IMyRepository rpo; public ServiceLayer(MyClassDataContext ctx) { context = ctx; rpo = new MyRepository(context); } private IQueryable<MyClass> ReadAllMyClass() { // pretend there is some complex business logic here // and maybe some filtering of the current users access to "all" // that I don't want to repeat in all of the public methods that access // MyClass objects. return rpo.ReadAllMyClass(); } public IEnumerable<MyClass> GetAllMyClass() { // call private IQueryable so we can do attional "in-database" processing return this.ReadAllMyClass(); } public IEnumerable<MyClass> GetActiveMyClass() { // call private IQueryable so we can do attional "in-database" processing // in this case a .Where() clause return this.ReadAllMyClass().Where(mc => mc.IsActive.Equals(true)); } #region "Something my class MAY need to do in the future" private IQueryable<MyOtherTable> ReadAllMyOtherTable() { // there could be additional constrains which define // "all" for the current user return context.MyOtherTable; } public IEnumerable<MyOtherTable> GetAllMyOtherTable() { return this.ReadAllMyOtherTable(); } public IEnumerable<MyOtherTable> GetInactiveOtherTable() { return this.ReadAllMyOtherTable.Where(ot => ot.IsActive.Equals(false)); } #endregion } This particular case is not the best illustration, since I could just call the repository directly in the GetActiveMyClass method, but let’s presume that my private IQueryable does some extra processing and business logic that I don't want to replicate in both of my public methods. Is that a bad way to attack an issue like this? I don't see it being so complex that it really warrants building a third class to sit between the repository and the service class, but I'd like to get your thoughts. For the sake of argument, lets presume two additional things. This service is going to be exposed through WCF and that each of these public IEnumerable methods will be calling a .Select(m => m.ToViewModel()) on each returned collection which will convert it to a POCO for serialization. The service will eventually need to expose some context.SomeOtherTable which wont be wrapped into the repository.

    Read the article

  • How to perform group by in LINQ and get a Iqueryable or a Custom Class Object?

    - by VJ
    Here is my query - var data = Goaldata.GroupBy(c => c.GoalId).ToList(); This returns a Igrouping object and I want an Iqueryable object which I can directly query to get the data while in this case I have to loop through using a foreach() and then get the data. Is there another way to group by in LINQ which returns directly a list of Iqueryable or the a List as similar to what happens for order by in LINQ.

    Read the article

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