Search Results

Search found 6252 results on 251 pages for 'linq expressions'.

Page 19/251 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • linq to xml. read. and assign to ViewData..noob

    - by raklos
    I have some xml similar to this: <?xml version="1.0" encoding="utf-8" ?> <data> <resources> <resource key="Title">Alpha</resource> <resource key="ImageName">Small.png</resource> <resource key="Desc">blah</resource> </resources> </data> using linq-xml how can i assign each resource here as a key value pair with the ViewData collection. Thanks.

    Read the article

  • How to get List of results from list of ID values with LINQ to SQL?

    - by DaveDev
    I have a list of ID values: List<int> MyIDs { get; set; } I'd like to pass this list to an interface to my repository and have it return a List that match the ID values I pass in. List<MyType> myTypes = new List<MyType>(); IMyRepository myRepos = new SqlMyRepository(); myTypes = myRepos.GetMyTypes(this.MyIDs); Currently, GetMyTypes() behaves similarly to this: public MyType GetMyTypes(int id) { return (from myType in db.MyTypes where myType.Id == id select new MyType { MyValue = myType.MyValue }).FirstOrDefault(); } where I iterate through MyIDs and pass each id in and add each result to a list. How do I need to change the LINQ so that I can pass in the full list of MyIDs and get a list of MyTypes out? GetMyTypes() would have a signature similar to public List<MyType> GetMyTypes(List<int> myIds)

    Read the article

  • LINQ-to-XML to DataGridView: Cannot edit fields -- How to fix?

    - by Pretzel
    I am currently doing LINQ-to-XML and populating a DataGridView with my query just fine. The trouble I am running into is that once loaded into the DataGridView, the values appear to be Un-editable (ReadOnly). Here's my code: var barcodes = (from src in xmldoc.Descendants("Container") where src.Descendants().Count() > 0 select new { Id = (string)src.Element("Id"), Barcode = (string)src.Element("Barcode"), Quantity = float.Parse((string)src.Element("Quantity").Attribute("value")) }).Distinct(); dataGridView1.DataSource = barcodes.ToList(); I read somewhere that the "DataGridView will be in ReadOnly mode when you use Anonymous types." But I couldn't find an explanation why or exactly what to do about it. Any ideas?

    Read the article

  • Extending LINQ classes to my own partial classes in different namespaces?

    - by sah302
    I have a .dbml file which of course contains the auto-generated classes based on my tables. I would however, like to extend them to my own classes. Typically I design such that each of my tables get their own namespace in their own folder containing all of their associated dao and service classes. So if I am dealing with a page that only has to do with 'customers' for instance, I can only include the customerNS. But when using LINQ I seem to be unable to do this. I have tried removing a default namespace from the project, I have tried putting the .dbml file into it's own folder with a custom namespace and then adding a 'using' statement, but no nothing works. I also saw the Entity Namespace, Context Namespace, and Custom Tool Namespace properties associated with the .dbml file and tried setting all these to names x and trying 'using x' in my other class to allow me to extend partial classes, but it just doesn't work. Is this possible or do I have to keep all extended partial classes in the same namespace as the .dbml file?

    Read the article

  • LINQ to SQL for tables across databases. Or View?

    - by BritishDeveloper
    I have a Message table and a User table. Both are in separate databases. There is a userID in the Message table that is used to join to the User table to find things like userName. How can I create this in LINQ to SQL? I can't seem to do a cross database join. Should I create a View in the database and use that instead? Will that work? What will happen to CRUD against it? E.g. if I delete a message - surely it won't delete the user? I'd imagine it would throw an error. What to do? I can't move the tables into the same database!

    Read the article

  • Using Linq, how to separate a list in to grouped objects by name?

    - by Dr. Zim
    I have a table where a record looks like this varchar(255) Name varchar(255) Text varchar(255) Value Name is the DDL name, Text is what is displayed, and Value is returned upon selection. There are between one and twenty options for each Name. Without iterating though each option like a cursor, is there any way to pull out a list of objects, one for each unique DDL Name, using Linq and C#? A sample of the data: Beds '4 (10)' 4 Beds '5 (1)' 5 Beds '7 (1)' 7 Baths 'NA (13)' NULL Baths '0 (1)' 0 Baths '1 (13)' 1 I was thinking about doing an outer select to get the unique Names, then an inner select to get the list of options for it, then return the set as a List of a set of Lists.

    Read the article

  • How to get rank from full-text search query with Linq to SQL?

    - by Stephen Jennings
    I am using Linq to SQL to call a stored procedure which runs a full-text search and returns the rank plus a few specific columns from the table Article. The rank column is the rank returned from the SQL function FREETEXTTABLE(). I've added this sproc to the data model designer with return type Article. This is working to get the columns I need; however, it discards the ranking of each search result. I'd like to get this information so I can display it to the user. So far, I've tried creating a new class RankedArticle which inherits from Article and adds the column Rank, then changing the return type of my sproc mapping to RankedArticle. When I try this, an InvalidOperationException gets thrown: Data member 'Int32 ArticleID' of type 'Heap.Models.Article' is not part of the mapping for type 'RankedArticle'. Is the member above the root of an inheritance hierarchy? I can't seem to find any other questions or Google results from people trying to get the rank column, so I'm probably missing something obvious here.

    Read the article

  • ASP.NET MVC 2: How to write this Linq SQL as a Dynamic Query (using strings)?

    - by Dr. Zim
    Skip to the "specific question" as needed. Some background: The scenario: I have a set of products with a "drill down" filter (Query Object) populated with DDLs. Each progressive DDL selection will further limit the product list as well as what options are left for the DDLs. For example, selecting a hammer out of tools limits the Product Sizes to only show hammer sizes. Current setup: I created a query object, sent it to a repository, and fed each option to a SQL "table valued function" where null values represent "get all products". I consider this a good effort, but far from DDD acceptable. I want to avoid any "programming" in SQL, hopefully doing everything with a repository. Comments on this topic would be appreciated. Specific question: How would I rewrite this query as a Dynamic Query? A link to something like 101 Linq Examples would be fantastic, but with a Dynamic Query scope. I really want to pass to this method the field in quotes "" for which I want a list of options and how many products have that option. (from p in db.Products group p by p.ProductSize into g select new Category { PropertyType = g.Key, Count = g.Count() }).Distinct(); Each DDL option will have "The selection (21)" where the (21) is the quantity of products that have that attribute. Upon selecting an option, all other remaining DDLs will update with the remaining options and counts.

    Read the article

  • Can I use the auto-generated Linq-to-SQL entity classes in 'disconnected' mode?

    - by Gary McGill
    Suppose I have an automatically-generated Employee class based on the Employees table in my database. Now suppose that I want to pass employee data to a ShowAges method that will print out name & age for a list of employees. I'll retrieve the data for a given set of employees via a linq query, which will return me a set of Employee instances. I can then pass the Employee instances to the ShowAges method, which can access the Name & Age fields to get the data it needs. However, because my Employees table has relationships with various other tables in my database, my Employee class also has a Department field, a Manager field, etc. that provide access to related records in those other tables. If the ShowAges method were to invoke any of those methods, this would cause lots more data to be fetched from the database, on-demand. I want to be sure that the ShowAges method only uses the data I have already fetched for it, but I really don't want to have to go to the trouble of defining a new class which replicates the Employee class but has fewer methods. (In my real-world scenario, the class would have to be considerably more complex than the Employee class described here; it would have several 'joined' classes that do need to be populated, and others that don't). Is there a way to 'switch off' or 'disconnect' the Employees instances so that an attempt to access any property or related object that's not already populated will raise an exception? If not, then I assume that since this must be a common requirement, there might be an already-established pattern for doing this sort of thing?

    Read the article

  • Can LINQ expression classes implement the observer pattern instead of deferred execution?

    - by Tormod
    Hi. We have issues within an application using a state machine. The application is implemented as a windows service and is iteration based (it "foreaches" itself through everything) and there are myriads of instances being processed by the state machine. As I'm reading the MEAP version of Jon Skeets book "C# in Depth, 2nd ed", I'm wondering if I can change the whole thing to use linq expression instances so that guards and conditions are represented using expression trees. We are building many applications on this state machine engine and would probably greatly benefit from the new Expression tree visualizer in VS 2010 Now, simple example. If I have an expression tree where there is an OR Expression condition with two sub nodes, is there any way that these can implement the observer pattern so that the expression tree becomes event driven? If a condition change, it should notify its parent node (the OR node). Since the OR node then changes from "false" to "true", then it should notify ITS parent and so on. I love the declarative model of expression trees, but the deferred execution model works in opposite direction of the control flow if you want event based "live" conditions. Am I off on a wild goose chase here? Or is there some concept in the BCL that may help me achieve this?

    Read the article

  • LINQ to SQL - How to efficiently do either an AND or an OR search for multiple criteria

    - by Dan Diplo
    I have an ASP.NET MVC site (which uses Linq To Sql for the ORM) and a situation where a client wants a search facility against a bespoke database whereby they can choose to either do an 'AND' search (all criteria match) or an 'OR' search (any criteria match). The query is quite complex and long and I want to know if there is a simple way I can make it do both without having to have create and maintain two different versions of the query. For instance, the current 'AND' search looks something like this (but this is a much simplified version): private IQueryable<SampleListDto> GetSampleSearchQuery(SamplesCriteria criteria) { var results = from r in Table where (r.Id == criteria.SampleId) && (r.Status.SampleStatusId == criteria.SampleStatusId) && (r.Job.JobNumber.StartsWith(criteria.JobNumber)) && (r.Description.Contains(criteria.Description)) select r; } I could copy this and replace the && with || operators to get the 'OR' version, but feel there must be a better way of achieving this. Does anybody have any suggestions how this can be achieved in an efficient and flexible way that is easy to maintain? Thanks.

    Read the article

  • [C#]How to introduce retry logic into LINQ to SQL to deal with timeouts?

    - by codemonkie
    I need to find ways to add retry mechanism to my DB calls in case of timeouts, LINQ to SQL is used to call some sprocs in my code... using (MyDataContext dc = new MyDataContext()) { int result = -1; //denote failure int count = 0; while ((result < 0) && (count < MAX_RETRIES)) { result = dc.myStoredProc1(...); count++; } result = -1; count = 0; while ((result < 0) && (count < MAX_RETRIES)) { result = dc.myStoredProc2(...); count++; } ... ... } Not sure if the code above is right or posed any complications. It'll be nice to throw an exception after MAX_RETRIES has reached, but I dunno how and where to throw them appropriately :-) Any helps appreciated.

    Read the article

  • Important question about linq to SQL performance on high loaded web applications

    - by Alex
    I started working with linq to SQL several weeks ago. I got really tired of working with SQL server directly through the SQL queries (sqldatareader, sqlcommand and all this good stuff).  After hearing about linq to SQL and mvc I quickly moved all my projects to these technologies. I expected linq to SQL work slower but it suprisongly turned out to be pretty fast, primarily because I always forgot to close my connections when using datareaders. Now I don't have to worry about it. But there's one problem that really bothers me. There's one page that's requested thousands of times a day. The system gets data in the beginning, works with it and updates it. Primarily the updates are ++ @ -- (increase and decrease values). I used to do it like this UPDATE table SET value=value+1 WHERE ID=@I'd It worked with no problems obviously. But with linq to SQL the data is taken in the beginning, moved to the class, changed and then saved. Stats.registeredusers++; Db.submitchanges(); Let's say there were 100 000 users. Linq will say "let it be 100 001" instead of "let it be increased by 1". But if there value of users has already been increased (that happens in my site all the time) then linq will be like oops, this value is already 100 001. Whatever I'll throw an exception" You can change this behavior so that it won't throw an exception but it still will not set the value to 100 002. Like I said, it happened with me all the time. The stas value was increased twice a second on average. I simply had to rewrite this chunk of code with classic ado net. So my question is how can you solve the problem with linq

    Read the article

  • LINQ Query using UDF that receives parameters from the query

    - by Ben Fidge
    I need help using a UDF in a LINQ which calculates a users position from a fixed point. int pointX = 567, int pointY = 534; // random points on a square grid var q = from n in _context.Users join m in _context.GetUserDistance(n.posY, n.posY, pointX, pointY, n.UserId) on n.UserId equals m.UserId select new User() { PosX = n.PosX, PosY = n.PosY, Distance = m.Distance, Name = n.Name, UserId = n.UserId }; The GetUserDistance is just a UDF that returns a single row in a TVP with that users distance from the points deisgnated in pointX and pointY variables, and the designer generates the following for it: [global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetUserDistance", IsComposable=true)] public IQueryable<GetUserDistanceResult> GetUserDistance([global::System.Data.Linq.Mapping.ParameterAttribute(Name="X1", DbType="Int")] System.Nullable<int> x1, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="X2", DbType="Int")] System.Nullable<int> x2, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="Y1", DbType="Int")] System.Nullable<int> y1, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="Y2", DbType="Int")] System.Nullable<int> y2, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="UserId", DbType="Int")] System.Nullable<int> userId) { return this.CreateMethodCallQuery<GetUserDistanceResult>(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), x1, x2, y1, y2, userId); } when i try to compile i get The name 'n' does not exist in the current context

    Read the article

  • linq: SQL performance on high loaded web applications

    - by Alex
    I started working with linq to SQL several weeks ago. I got really tired of working with SQL server directly through the SQL queries (sqldatareader, sqlcommand and all this good stuff).  After hearing about linq to SQL and mvc I quickly moved all my projects to these technologies. I expected linq to SQL work slower but it suprisongly turned out to be pretty fast, primarily because I always forgot to close my connections when using datareaders. Now I don't have to worry about it. But there's one problem that really bothers me. There's one page that's requested thousands of times a day. The system gets data in the beginning, works with it and updates it. Primarily the updates are ++ @ -- (increase and decrease values). I used to do it like this UPDATE table SET value=value+1 WHERE ID=@I'd It worked with no problems obviously. But with linq to SQL the data is taken in the beginning, moved to the class, changed and then saved. Stats.registeredusers++; Db.submitchanges(); Let's say there were 100 000 users. Linq will say "let it be 100 001" instead of "let it be increased by 1". But if there value of users has already been increased (that happens in my site all the time) then linq will be like oops, this value is already 100 001. Whatever I'll throw an exception" You can change this behavior so that it won't throw an exception but it still will not set the value to 100 002. Like I said, it happened with me all the time. The stas value was increased twice a second on average. I simply had to rewrite this chunk of code with classic ado net. So my question is how can you solve the problem with linq

    Read the article

  • How to write this Linq SQL as a Dynamic Query (using strings)?

    - by Dr. Zim
    Skip to the "specific question" as needed. Some background: The scenario: I have a set of products with a "drill down" filter (Query Object) populated with DDLs. Each progressive DDL selection will further limit the product list as well as what options are left for the DDLs. For example, selecting a hammer out of tools limits the Product Sizes to only show hammer sizes. Current setup: I created a query object, sent it to a repository, and fed each option to a SQL "table valued function" where null values represent "get all products". I consider this a good effort, but far from DDD acceptable. I want to avoid any "programming" in SQL, hopefully doing everything with a repository. Comments on this topic would be appreciated. Specific question: How would I rewrite this query as a Dynamic Query? A link to something like 101 Linq Examples would be fantastic, but with a Dynamic Query scope. I really want to pass to this method the field in quotes "" for which I want a list of options and how many products have that option. from p in db.Products group p by p.ProductSize into g select new Category { PropertyType = g.Key, Count = g.Count() } Each DDL option will have "The selection (21)" where the (21) is the quantity of products that have that attribute. Upon selecting an option, all other remaining DDLs will update with the remaining options and counts. Edit: Additional notes: .OrderBy("it.City") // "it" refers to the entire record .GroupBy("City", "new(City)") // This produces a unique list of City .Select("it.Count()") //This gives a list of counts... getting closer .Select("key") // Selects a list of unique City .Select("new (key, count() as string)") // +1 to me LOL. key is a row of group .GroupBy("new (City, Manufacturer)", "City") // New = list of fields to group by .GroupBy("City", "new (Manufacturer, Size)") // Second parameter is a projection Product .Where("ProductType == @0", "Maps") .GroupBy("new(City)", "new ( null as string)")// Projection not available later? .Select("new (key.City, it.count() as string)")// GroupBy new makes key an object Product .Where("ProductType == @0", "Maps") .GroupBy("new(City)", "new ( null as string)")// Projection not available later? .Select("new (key.City, it as object)")// the it object is the result of GroupBy var a = Product .Where("ProductType == @0", "Maps") .GroupBy("@0", "it", "City") // This fails to group Product at all .Select("new ( Key, it as Product )"); // "it" is property cast though What I have learned so far is LinqPad is fantastic, but still looking for an answer. Eventually, completely random research like this will prevail I guess. LOL. Edit:

    Read the article

  • Linq Left Outer Join

    - by Neil
    I am new to LINQ and am trying to convert a SQL query to LINQ: SQL: left outer join PRODUCT_BEST_USE pbu on pbu.PRODUCT_GUID = @uProductId and pbu.BEST_USE_GUID = bu.BEST_USE_GUID LINQ: from PBU in PRODUCT_BEST_USE.Where(PBU=>PBU.PRODUCT_GUID == p.PRODUCT_GUID).DefaultIfEmpty() When I add and PBU.BEST_USE_GUID equals BU.BEST_USE_GUID, I get an error: "A query body must end with a select clause or a group clause" Here is the full Linq query: from p in PRODUCT join BU in BEST_USE on p.CATEGORY_GUID equals BU.CATEGORY_GUID from PBU in PRODUCT_BEST_USE.Where(PBU=>PBU.PRODUCT_GUID == p.PRODUCT_GUID).DefaultIfEmpty() and PBU.BEST_USE_GUID equals BU.BEST_USE_GUID where p.PRODUCT_GUID == new Guid("d317752b-581d-4f43-92fa-4a4af91009f5") select new { BU.NAME, PBU.PRODUCT_BEST_USE_GUID }

    Read the article

  • Linq To Sql or classic ADO.net?

    - by Spyros
    I am asking my self many times before start writting a new app or data access library , should I use LinqToSql or classic ADO.net , I have used both and the development time I spend on building an app with Linq To sql is like the 1/3 compared to ADO.net. The only think I like using Linq to sql is that I dont have to design the domain objects Linq does that for me and saves me from spend my time on boring things :P But is Linq to sql suitable for large scale projects , is there an overhead that we can avoid when using ADO.net ?

    Read the article

  • Future of Linq to Sql and Entity Framework

    - by ENES TAYLAN
    I work on a project and want to use an ORM. What should I use: Linq to Sql or Entity Framework? Linq to Sql provides more opportunities, as I see, for example support for enumeration types. However, also it is said that, Linq to Sql was for playing and learning for Linq and future strategy of Microsoft lies on Entity Framework. So which one should I use?

    Read the article

  • Linq To Text Files

    - by j-t-s
    Hi All I have a Text File (Sorry, I'm not allowed to work on XML files :(), and it includes customer records. Each text file looks like: Account_ID: 98734BLAH9873 User Name: something_85 First Name: ILove Last Name: XML Age: 209 etc... And I need to be able to use LINQ to get the data from these text files and just store them in memory. I have seen many Linq to SQL, Linq to BLAH but nothing for Linq to Text. Can someone please help me out abit? Thank you

    Read the article

  • Regular Expressions Quick Reference

    - by Jan Goyvaerts
    The Regular-Expressions.info website has a new quick reference to regular expressions that lists all of the regex syntax in one single table along with a link to the tutorial section that explains the syntax. The quick reference is ordered by syntax whereas the full reference tables are ordered by feature. There are multiple entries for some of the syntax as different regex flavors may use the same syntax for different features. Use the quick reference if you’ve seen some syntax in somebody else’s regex and you have no idea what feature that syntax is for. Use the full reference tables if you already know the feature you want but forgot which syntax to use. Of course, an even quicker reference is to paste your regex into RegexBuddy, select the application you’re working with, and click on the part of the regex you don’t understand. RegexBuddy then selects the corresponding node in its regex tree which summarizes exactly what the syntax you clicked on does in your regex. If you need more information, press F1 or click the Explain Token button to open the relevant page in the regex tutorial in RegexBuddy’s help file.

    Read the article

  • Regular Expressions Cookbook Ebook Deal of the Day

    - by Jan Goyvaerts
    Every day O’Reilly has an “ebook deal of the day” offering one or a bunch of their books in electronic format for only $9.99. Twice this year I received an email from O’Reilly notifying me that Regular Expressions Cookbook was on sale. But each time the email was sent on the morning of the day itself. When it’s morning in California it’s already bedtime for me here in Thailand. So I never saw the emails until the next day, making it rather pointless to blog about the deal. But this time O’Reilly has listened to my request for advance notification. I just got an email this morning saying Regular Expressions Cookbook will be part of the Ebook Deal of the Day for 15 September 2010. That’s 15 September on the US west coast. When I write this there’s a few hours to go before the deal starts at one past midnight California time. You can get any O’Reilly Cookbook as an ebook for only $9.99. The normal price for Regular Expressons Cookbook as an ebook is $31.99. The download includes the book in PDF, ePub, Mobi (for Kindle), DAISY, and Android formats.

    Read the article

  • Multiple Conditions in Lambda Expressions at runtime C#

    - by Ryan
    Hi, I would like to know how to be able to make an Expression tree by inputting more than one parameter Example: dataContext.Users.Where(u => u.username == "Username" && u.password == "Password") At the moment the code that I did was the following but would like to make more general in regards whether the condition is OR or AND public Func<TLinqEntity, bool> ANDOnlyParams(string[] paramNames, object[] values) { List<ParameterExpression> paramList = new List<ParameterExpression>(); foreach (string param in paramNames) { paramList.Add(Expression.Parameter(typeof(TLinqEntity), param)); } List<LambdaExpression> lexList = new List<LambdaExpression>(); for (int i = 0; i < paramNames.Length; i++) { if (i == 0) { Expression bodyInner = Expression.Equal( Expression.Property( paramList[i], paramNames[i]), Expression.Constant(values[i])); lexList.Add(Expression.Lambda(bodyInner, paramList[i])); } else { Expression bodyOuter = Expression.And( Expression.Equal( Expression.Property( paramList[i], paramNames[i]), Expression.Constant(values[i])), Expression.Invoke(lexList[i - 1], paramList[i])); lexList.Add(Expression.Lambda(bodyOuter, paramList[i])); } } return ((Expression<Func<TLinqEntity, bool>>)lexList[lexList.Count - 1]).Compile(); } Thanks

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >