Search Results

Search found 6744 results on 270 pages for 'linq to entities'.

Page 15/270 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • LINQ for SQL Developers and DBA’s

    - by AtulThakor
    Firstly I’d just like to thank the guys who organise the SQL Server User Group (Martin/Tony/Chris) and for giving me the opportunity to speak at the recent event. Sorry about the slides taking so long but here they are along with some extra information. Firstly the demo’s were all done using LINQPad 4.0 which can be downloaded here: http://www.linqpad.net/ There are 2 versions 3.5/4.0 With 3.5 you should be able to replicate the problem I showed where a query using a parameter which is X characters long would create a different execution plan to a query which uses a parameter which is Y characters long, otherwise I would just use 4.0 The sample database used is AdventureWorksLT2008 which can be downloaded from here: http://msftdbprodsamples.codeplex.com/releases/view/37109 The scripts have been named so that you can select the appropriate way to run them i.e.: C# expression / C#statement, each script can be run individually be highlighting the query and clicking the play symbol or hitting F5. Scripts and Slides: http://sqlblogcasts.com/blogs/atulthakor/An%20Introduction%20to%20LINQ.zip Please don't hesitate in sending any questions via email/twitter, I’ll try my best to answer your questions! Thanks, Atul

    Read the article

  • Grouping data in LINQ with the help of group keyword

    - by vik20000in
    While working with any kind of advanced query grouping is a very important factor. Grouping helps in executing special function like sum, max average etc to be performed on certain groups of data inside the date result set. Grouping is done with the help of the Group method. Below is an example of the basic group functionality.     int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };         var numberGroups =         from num in numbers         group num by num % 5 into numGroup         select new { Remainder = numGroup.Key, Numbers = numGroup };  In the above example we have grouped the values based on the reminder left over when divided by 5. First we are grouping the values based on the reminder when divided by 5 into the numgroup variable.  numGroup.Key gives the value of the key on which the grouping has been applied. And the numGroup itself contains all the records that are contained in that group. Below is another example to explain the same. string[] words = { "blueberry", "abacus", "banana", "apple", "cheese" };         var wordGroups =         from num in words         group num by num[0] into grp         select new { FirstLetter = grp.Key, Words = grp }; In the above example we are grouping the value with the first character of the string (num[0]). Just like the order operator the group by clause also allows us to write our own logic for the Equal comparison (That means we can group Item by ignoring case also by writing out own implementation). For this we need to pass an object that implements the IEqualityComparer<string> interface. Below is an example. public class AnagramEqualityComparer : IEqualityComparer<string> {     public bool Equals(string x, string y) {         return getCanonicalString(x) == getCanonicalString(y);     }      public int GetHashCode(string obj) {         return getCanonicalString(obj).GetHashCode();     }         private string getCanonicalString(string word) {         char[] wordChars = word.ToCharArray();         Array.Sort<char>(wordChars);         return new string(wordChars);     } }  string[] anagrams = {"from   ", " salt", " earn", "  last   ", " near "}; var orderGroups = anagrams.GroupBy(w => w.Trim(), new AnagramEqualityComparer()); Vikram  

    Read the article

  • LINQ: Enhancing Distinct With The SelectorEqualityComparer

    - by Paulo Morgado
    On my last post, I introduced the PredicateEqualityComparer and a Distinct extension method that receives a predicate to internally create a PredicateEqualityComparer to filter elements. Using the predicate, greatly improves readability, conciseness and expressiveness of the queries, but it can be even better. Most of the times, we don’t want to provide a comparison method but just to extract the comaprison key for the elements. So, I developed a SelectorEqualityComparer that takes a method that extracts the key value for each element. Something like this: public class SelectorEqualityComparer<TSource, Tkey> : EqualityComparer<TSource> where Tkey : IEquatable<Tkey> { private Func<TSource, Tkey> selector; public SelectorEqualityComparer(Func<TSource, Tkey> selector) : base() { this.selector = selector; } public override bool Equals(TSource x, TSource y) { Tkey xKey = this.GetKey(x); Tkey yKey = this.GetKey(y); if (xKey != null) { return ((yKey != null) && xKey.Equals(yKey)); } return (yKey == null); } public override int GetHashCode(TSource obj) { Tkey key = this.GetKey(obj); return (key == null) ? 0 : key.GetHashCode(); } public override bool Equals(object obj) { SelectorEqualityComparer<TSource, Tkey> comparer = obj as SelectorEqualityComparer<TSource, Tkey>; return (comparer != null); } public override int GetHashCode() { return base.GetType().Name.GetHashCode(); } private Tkey GetKey(TSource obj) { return (obj == null) ? (Tkey)(object)null : this.selector(obj); } } Now I can write code like this: .Distinct(new SelectorEqualityComparer<Source, Key>(x => x.Field)) And, for improved readability, conciseness and expressiveness and support for anonymous types the corresponding Distinct extension method: public static IEnumerable<TSource> Distinct<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IEquatable<TKey> { return source.Distinct(new SelectorEqualityComparer<TSource, TKey>(selector)); } And the query is now written like this: .Distinct(x => x.Field) For most usages, it’s simpler than using a predicate.

    Read the article

  • how to update child records when updating the Master table using Linq [closed]

    - by user20358
    I currently use a general repositry class that can update only a single table like so public abstract class MyRepository<T> : IRepository<T> where T : class { protected IObjectSet<T> _objectSet; protected ObjectContext _context; public MyRepository(ObjectContext Context) { _objectSet = Context.CreateObjectSet<T>(); _context = Context; } public IQueryable<T> GetAll() { return _objectSet.AsQueryable(); } public IQueryable<T> Find(Expression<Func<T, bool>> filter) { return _objectSet.Where(filter); } public void Add(T entity) { _objectSet.AddObject(entity); _context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Added); _context.SaveChanges(); } public void Update(T entity) { _context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified); _context.SaveChanges(); } public void Delete(T entity) { _objectSet.Attach(entity); _context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Deleted); _objectSet.DeleteObject(entity); _context.SaveChanges(); } } For every table class generated by my EDMX designer I create another class like this public class CustomerRepo : MyRepository<Customer> { public CustomerRepo (ObjectContext context) : base(context) { } } for any updates that I need to make to a particular table I do this: Customer CustomerObj = new Customer(); CustomerObj.Prop1 = ... CustomerObj.Prop2 = ... CustomerObj.Prop3 = ... CustomerRepo.Update(CustomerObj); This works perfectly well when I am updating just to the specific table called Customer. Now if I need to also update each row of another table which is a child of Customer called Orders what changes do I need to make to the class MyRepository. Orders table will have multiple records for a Customer record and multiple fields too, say for example Field1, Field2, Field3. So my questions are: 1.) If I only need to update Field1 of the Orders table for some rows based on a condition and Field2 for some other rows based on a different condition then what changes I need to do? 2.) If there is no such condition and all child rows need to be updated with the same value for all rows then what changes do I need to do? Thanks for taking the time. Look forward to your inputs...

    Read the article

  • LINQ – Skip() and Take() methods

    - by nmarun
    I had this issue recently where I have an array of integers and I’m doing some Skip(n) and then a Take(m) on the collection. Here’s an abstraction of the code: 1: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 2: var taken = numbers.Skip(3).Take(3); 3: foreach (var i in taken) 4: { 5: Console.WriteLine(i); 6: } The output is as expected: 3, 9, 8 – skip the first three and then take the next three items. But, what happens if I do something like: 1: var taken = numbers.Skip(7).Take(5); In English – skip the first seven and the take the next 5 items from an array that contains only 10 elements. Think it’ll throw the IndexOutOfRangeException exception? Nope. These extension methods are a little smarter than that. Even though the user has requested more elements than what exists in the collection, the Take method only returns the first three thereby making the output of the program as: 7, 2, 0. The scenario is handled similarly when you do: 1: var taken = numbers.Take(5).Skip(7); This one takes the first 5 elements from the numbers array and then skips 7 of them. This is what is looks like in the debug mode: Just wanted to share this behavior.

    Read the article

  • How to use Linq to select and group complex child object from a parents list.

    - by Daoming Yang
    How to use Linq to select and group complex child object from a parents list. I have an OrderList each of order object has a OrderProductVariantList(OrderLineList), and each of OrderProductVariant object has ProductVariant, and then the ProductVariant object will have a Product object which contains product information. My goal is to select and group the most popular products from the order list. Can anyone help me with this? Many thanks.

    Read the article

  • Will this LINQ-TO-SQL query fetch all records from the table ?

    - by Puneet Dudeja
    public long GetNewCRN() { return ((from c in DataContext.GetTable<Cust_Master>() select c.CUSTSERH_CRN).Max() + 1); } Will this Linq to Sql query fetch all records from the table first and then select the maximum of the column ? If yes, then isn't it a bad idea using linq to sql instead of normal SqlCommand ? Or is there any other way of doing it in linq to sql ? When I attach Console.Out, I see nothing(command prompt does not even open). But when I include following:- context.Log = new System.IO.StreamWriter("d:\\abcd.txt"); I get an error, that "The process can not access the file because it is being used by another process" and that process is "w3wp.exe". How can I see the sql commands being executed by DataContext then ?

    Read the article

  • Hype and LINQ

    - by Tony Davis
    "Tired of querying in antiquated SQL?" I blinked in astonishment when I saw this headline on the LinqPad site. Warming to its theme, the site suggests that what we need is to "kiss goodbye to SSMS", and instead use LINQ, a modern query language! Elsewhere, there is an article entitled "Why LINQ beats SQL". The designers of LINQ, along with many DBAs, would, I'm sure, cringe with embarrassment at the suggestion that LINQ and SQL are, in any sense, competitive ways of doing the same thing. In fact what LINQ really is, at last, is an efficient, declarative language for C# and VB programmers to access or manipulate data in objects, local data stores, ORMs, web services, data repositories, and, yes, even relational databases. The fact is that LINQ is essentially declarative programming in a .NET language, and so in many ways encourages developers into a "SQL-like" mindset, even though they are not directly writing SQL. In place of imperative logic and loops, it uses various expressions, operators and declarative logic to build up an "expression tree" describing only what data is required, not the operations to be performed to get it. This expression tree is then parsed by the language compiler, and the result, when used against a relational database, is a SQL string that, while perhaps not always perfect, is often correctly parameterized and certainly no less "optimal" than what is achieved when a developer applies blunt, imperative logic to the SQL language. From a developer standpoint, it is a mistake to consider LINQ simply as a substitute means of querying SQL Server. The strength of LINQ is that that can be used to access any data source, for which a LINQ provider exists. Microsoft supplies built-in providers to access not just SQL Server, but also XML documents, .NET objects, ADO.NET datasets, and Entity Framework elements. LINQ-to-Objects is particularly interesting in that it allows a declarative means to access and manipulate arrays, collections and so on. Furthermore, as Michael Sorens points out in his excellent article on LINQ, there a whole host of third-party LINQ providers, that offers a simple way to get at data in Excel, Google, Flickr and much more, without having to learn a new interface or language. Of course, the need to be generic enough to deal with a range of data sources, from something as mundane as a text file to as esoteric as a relational database, means that LINQ is a compromise and so has inherent limitations. However, it is a powerful and beautifully compact language and one that, at least in its "query syntax" guise, is accessible to developers and DBAs alike. Perhaps there is still hope that LINQ can fulfill Phil Factor's lobster-induced fantasy of a language that will allow us to "treat all data objects, whether Word files, Excel files, XML, relational databases, text files, HTML files, registry files, LDAPs, Outlook and so on, in the same logical way, as linked databases, and extract the metadata, create the entities and relationships in the same way, and use the same SQL syntax to interrogate, create, read, write and update them." Cheers, Tony.

    Read the article

  • Allocating Entities within an Entity System

    - by miguel.martin
    I'm quite unsure how I should allocate/resemble my entities within my entity system. I have various options, but most of them seem to have cons associated with them. In all cases entities are resembled by an ID (integer), and possibly has a wrapper class associated with it. This wrapper class has methods to add/remove components to/from the entity. Before I mention the options, here is the basic structure of my entity system: Entity An object that describes an object within the game Component Used to store data for the entity System Contains entities with specific components Used to update entities with specific components World Contains entities and systems for the entity system Can create/destroy entites and have systems added/removed from/to it Here are my options, that I have thought of: Option 1: Do not store the Entity wrapper classes, and just store the next ID/deleted IDs. In other words, entities will be returned by value, like so: Entity entity = world.createEntity(); This is much like entityx, except I see some flaws in this design. Cons There can be duplicate entity wrapper classes (as the copy-ctor has to be implemented, and systems need to contain entities) If an Entity is destroyed, the duplicate entity wrapper classes will not have an updated value Option 2: Store the entity wrapper classes within an object pool. i.e. Entities will be return by pointer/reference, like so: Entity& e = world.createEntity(); Cons If there is duplicate entities, then when an entity is destroyed, the same entity object may be re-used to allocate another entity. Option 3: Use raw IDs, and forget about the wrapper entity classes. The downfall to this, I think, is the syntax that will be required for it. I'm thinking about doing thisas it seems the most simple & easy to implement it. I'm quite unsure about it, because of the syntax. i.e. To add a component with this design, it would look like: Entity e = world.createEntity(); world.addComponent<Position>(e, 0, 3); As apposed to this: Entity e = world.createEntity(); e.addComponent<Position>(0, 3); Cons Syntax Duplicate IDs

    Read the article

  • Extend linq-to-sql partial class to avoid writing a property?

    - by Curtis White
    I have a linq-to-sql class. I have a property "Password" for which I want to call the underlying ASP.NET Membership provider. Thus, I do not want this property written out directly but via my own code. I basically want to create a facade/proxy for this property such that I may use the underlying membership provider or a custom stored procedure. I want to accomplish without modifying the LINQ-TO-SQL designer generated code, if at all possible.

    Read the article

  • Linq 2 Sybase ASE database? What are the options?

    - by Scott Weinstein
    I have a need to query an existing Sybase ASE database and would like to use Linq syntax for my data retrival. I don't need write access, nor do I need the full set of Linq operators, just Select(), SelectMany(), Where(), and GroupJoin() What are options are available? In particular, I'm wondering about nHibernate and building a new Linq2Sybase provider based on the IQ toolkit.

    Read the article

  • What is the difference between these 2 XML LINQ Queries?

    - by Jon
    I have the 2 following LINQ queries and I haven't quite got my head around LINQ so what is the difference between the 2 approaches below? Is there a circumstance where one approach is better than another? ChequeDocument.Descendants("ERRORS").Where(x=>(string)x.Attribute("D") == "").Count(); (from x in ChequeDocument.Descendants("ERRORS") where (string)x.Attribute("D") == "" select x).Count())

    Read the article

  • How to use LINQ for CRUD with a simple SQL table?

    - by Rob Ferno
    Every LINQ blog I found there seemed around 2 years old, I understand the syntax but need more direction on creating the SQL mapping and context classes. I just need to use LINQ for 2 SQL tables I have, nothing complicated. Do folks write the SQL mapping classes by hand for such cases or is there a decent tool for this? Can someone point me in the right direction?

    Read the article

  • How can I use external expressions in Linq with EF4 (and LINQKit)?

    - by neo
    I want to separate out often used expressions in linq queries. I'm using Entity Framework 4 and also LINQKit but I still don't know how I should do it the right way. Let me give you an example: Article article = dataContainer.Articles.FirstOrDefault(a => a.Id == id); IEnumerable<Comment> comments = (from c in container.Comments where CommentExpressions.IsApproved.Invoke(c) select c); public static class CommentExpressions { public static Expression<Func<Module, bool>> IsApproved { get { return m => m.IsApproved; } } } Of course the IsApproved expression would be something much more complicated. The problem is that the Invoke() won't work because I didn't call .asExpandable() from LINQKit on container.Comments but I can't call it because it's just an ICollection instead of an ObjectSet. So my question is: Do I always have to go through the data context when I want to include external expressions or can I somehow use it on the object I fetched (Article)? Any ideas or best practices? Thanks very much! neo

    Read the article

  • Is it just me? I find LINQ to XML to be sort of cumbersome, compared to XPath.

    - by Cheeso
    I am a C# programmer, so I don't get to take advantage of the cool XML syntax in VB. Dim itemList1 = From item In rss.<rss>.<channel>.<item> _ Where item.<description>.Value.Contains("LINQ") Or _ item.<title>.Value.Contains("LINQ") Using C#, I find XPath to be easier to think about, easier to code, easier to understand, than performing a multi-nested select using LINQ to XML. Look at this syntax, it looks like Greek swearing: var waypoints = from waypoint in gpxDoc.Descendants(gpx + "wpt") select new { Latitude = waypoint.Attribute("lat").Value, Longitude = waypoint.Attribute("lon").Value, Elevation = waypoint.Element(gpx + "ele") != null ? waypoint.Element(gpx + "ele").Value : null, Name = waypoint.Element(gpx + "name") != null ? waypoint.Element(gpx + "name").Value : null, Dt = waypoint.Element(gpx + "cmt") != null ? waypoint.Element(gpx + "cmt").Value : null }; All the casting, the heavy syntax, the possibility for NullPointerExceptions. None of this happens with XPath. I like LINQ in general, and I use it on object collections and databases, but my first go-round with querying XML led me right back to XPath. Is it just me? Am I missing something? EDIT: someone voted to close this as "not a real question". But it is a real question, stated clearly. The question is: Am I misunderstanding something with LINQ to XML?

    Read the article

  • How can I stop an auto-generated Linq to SQL class from loading ALL data?

    - by Gary McGill
    DUPLICATE of http://stackoverflow.com/questions/2433422/how-can-i-stop-an-auto-generated-linq-to-sql-class-from-loading-all-data post answers there! I have an ASP.NET MVC project, much like the NerdDinner tutorial example. (I'm using MVC 2, but followed the NerdDinner tutorial in order to create it). As per the instructions in part 3 of the tutorial, I've created a Linq-to-SQL model of my database by creating a "Linq to SQL Classes" (.dbml) surface, and dropping my database tables onto it. The designer has automatically added relationships between the generated classes based on my database tables. Let's say that my classes are as per the NerdDinner example, so I have Dinner and RSVP tables, where each Dinner record is associated with many RSVP records - hence in the generated classes, the Dinner object has a RSVPs property which is a list of RSVP objects. My problem is this: it appears (and I'd be gladly proved wrong on this) that as soon as I access a Dinner object, it's loading all of the corresponding RSVP objects, even if I don't use the RSVPs member. First question: is this really the default behavior for the generated classes? In my particular situation, the object graph contains many more tables (which have an order of magnitude more records), and so this is disastrous behaviour - I'd be loading tons of data when all I want to do is show the details of a single parent record. Second question: are there any properties exposed through the designer UI that would let me modify this behavior? (I can't find any). Third question: I've seen a description of how to control the loading of related records in a DataContext by using a DataShape object associated with the DataContext. Is that what I'm meant to do, and if so are there any tutorials like the NerdDinner one that would show not only how to do it, but also suggest a 'pattern' for normal use?

    Read the article

  • How can I create a dynamic LINQ query in C# with possible multiple group by clauses?

    - by FordPrefect141
    I have been a programmer for some years now but I am a newcomer to LINQ and C# so forgive me if my question sounds particularly stupid. I hope someone may be able to point me in the right direction. My task is to come up with the ability to form a dynamic multiple group by linq query within a c# script using a generic list as a source. For example, say I have a list containing multiple items with the following structure: FieldChar1 - character FieldChar2 - character FieldChar3 - character FieldNum1 - numeric FieldNum2 - numeric In a nutshell I want to be able to create a LINQ query that will sum FieldNum1 and FieldNum2 grouped by any one, two or all three of the FieldChar fields that will be decided at runtime depending on the users requirements as well as selecting the FieldChar fields in the same query. I have the dynamic.cs in my project which icludes a GroupByMany extension method but I have to admit I am really not sure how to put these to use. I am able to get the desired results if I use a query with hard-wired group by requests but not dynamically. Apologies for any erroneous nomenclature, I am new to this language but any advice would be most welcome. Many thanks Alex

    Read the article

  • LINQ thinks I need an extra INNER JOIN, but why?

    - by Saurabh Kumar
    I have a LINQ query, which for some reason is generating an extra/duplicatre INNER JOIN. This is causing the query to not return the expected output. If I manually comment that extra JOIN from the generated SQL, then I get seemingly correct output. Can you detect what I might have done i nthis LINQ to have cuased this extra JOIN? Thanks. Here is my approx LINQ var ids = context.Code.Where(predicate); var rs = from r in ids group r by new { r.phonenumbers.person.PersonID} into g let matchcount=g.Select(p => p.phonenumbers.PhoneNum).Distinct().Count() where matchcount ==2 select new { personid = g.Key }; and here is the generated SQL (the duplicate join is [t7]) Declare @p1 VarChar(10)='Home' Declare @p2 VarChar(10)='111' Declare @p3 VarChar(10)='Office' Declare @p4 VarChar(10)='222' Declare @p5 int=2 SELECT [t9].[PersonID] AS [pid] FROM ( SELECT [t3].[PersonID], ( SELECT COUNT(*) FROM ( SELECT DISTINCT [t7].[PhoneValue] FROM [dbo].[Person] AS [t4] INNER JOIN [dbo].[PersonPhoneNumber] AS [t5] ON [t5].[PersonID] = [t4].[PersonID] INNER JOIN [dbo].[CodeMaster] AS [t6] ON [t6].[Code] = [t5].[PhoneType] INNER JOIN [dbo].[PersonPhoneNumber] AS [t7] ON [t7].[PersonID] = [t4].[PersonID] WHERE ([t3].[PersonID] = [t4].[PersonID]) AND ([t6].[Enumeration] = @p0) AND ((([t6].[CodeDescription] = @p1) AND ([t5].[PhoneValue] = @p2)) OR (([t6].[CodeDescription] = @p3) AND ([t5].[PhoneValue] = @p4))) ) AS [t8] ) AS [value] FROM ( SELECT [t0].[PersonID] FROM [dbo].[Person] AS [t0] INNER JOIN [dbo].[PersonPhoneNumber] AS [t1] ON [t1].[PersonID] = [t0].[PersonID] INNER JOIN [dbo].[CodeMaster] AS [t2] ON [t2].[Code] = [t1].[PhoneType] WHERE ([t2].[Enumeration] = @p0) AND ((([t2].[CodeDescription] = @p1) AND ([t1].[PhoneValue] = @p2)) OR (([t2].[CodeDescription] = @p3) AND ([t1].[PhoneValue] = @p4))) GROUP BY [t0].[PersonID] ) AS [t3] ) AS [t9] WHERE [t9].[value] = @p5

    Read the article

  • Linq-to-SQL produces bad SQL?

    - by strager
    I am trying to run a Linq-to-SQL query, but when the query is evaluated, I get the following exception: System.Data.OleDb.OleDbException was unhandled Message=The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect. Source=Microsoft JET Database Engine ErrorCode=-2147217900 StackTrace: at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.OleDb.OleDbCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader() at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source) at xxx.InventoryPopulator`2.Clear(String barcode) in F:\Projects\C#\xxx\xxx\InventoryPopulator.cs:line 38 [..etc..] InnerException: The debugger shows my query is: SELECT [t0].[SupplierID] AS [Id], [t0].[SupplierSKU] AS [Sku], [t0].[LocalSKU] AS [LocalSku], [t0].[ManufacturersBarcode] AS [Barcode], [t0].[QuantityAvailable] FROM [inventorySupplier] AS [t0] WHERE [t0].[ManufacturersBarcode] = @p0 And the Linq query which generates the above is: var items = from item in this.supplierItems where item.Barcode == barcode select item; How do I fix my query?

    Read the article

  • Is this an example of LINQ-to-SQL?

    - by Edward Tanguay
    I made a little WPF application with a SQL CE database. I built the following code with LINQ to get data out of the database, which was surprisingly easy. So I thought "this must be LINQ-to-SQL". Then I did "add item" and added a "LINQ-to-SQL classes" .dbml file, dragged my table onto the Object Relational Designer but it said, "The selected object uses an unsupported data provider." So then I questioned whether or not the following code actually is LINQ-to-SQL, since it indeed allows me to access data from my SQL CE database file, yet officially "LINQ-to-SQL" seems to be unsupported for SQL CE. So is the following "LINQ-to-SQL" or not? using System.Linq; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Windows; namespace TestLinq22 { public partial class Window1 : Window { public Window1() { InitializeComponent(); MainDB db = new MainDB(@"Data Source=App_Data\Main.sdf"); var customers = from c in db.Customers select new {c.FirstName, c.LastName}; TheListBox.ItemsSource = customers; } } [Database(Name = "MainDB")] public class MainDB : DataContext { public MainDB(string connection) : base(connection) { } public Table<Customers> Customers; } [Table(Name = "Customers")] public class Customers { [Column(DbType = "varchar(100)")] public string FirstName; [Column(DbType = "varchar(100)")] public string LastName; } }

    Read the article

  • Pass Linq Expression to a function

    - by Kushan Hasithe Fernando
    I want to pass a property list of a class to a function. with in the function based on property list I'm going to generate a query. As exactly same functionality in Linq Select method. Here I'm gonna implement this for Ingress Database. As an example, in front end I wanna run a select as this, My Entity Class is like this public class Customer { [System.Data.Linq.Mapping.ColumnAttribute(Name="Id",IsPrimaryKey=true)] public string Id { get; set; } [System.Data.Linq.Mapping.ColumnAttribute(Name = "Name")] public string Name { get; set; } [System.Data.Linq.Mapping.ColumnAttribute(Name = "Address")] public string Address { get; set; } [System.Data.Linq.Mapping.ColumnAttribute(Name = "Email")] public string Email { get; set; } [System.Data.Linq.Mapping.ColumnAttribute(Name = "Mobile")] public string Mobile { get; set; } } I wanna call a Select function like this, var result = dataAccessService.Select<Customer>(C=>C.Name,C.Address); then,using result I can get the Name and Address properties' values. I think my Select function should looks like this, ( *I think this should done using Linq Expression. But im not sure what are the input parameter and return type. * ) Class DataAccessService { // I'm not sure about this return type and input types, generic types. public TResult Select<TSource,TResult>(Expression<Func<TSource,TResult>> selector) { // Here using the property list, // I can get the ColumnAttribute name value and I can generate a select query. } } This is a attempt to create a functionality like in Linq. But im not an expert in Linq Expressions. There is a project call DbLinq from MIT, but its a big project and still i couldn't grab anything helpful from that. Can someone please help me to start this, or can someone link me some useful resources to read about this.

    Read the article

  • How do I tell the cases when it's worth to use LINQ?

    - by Lijo
    Many things in LINQ can be accomplished without the library. But for some scenarios, LINQ is most appropriate. Examples are: SELECT - http://stackoverflow.com/questions/11883262/wrapping-list-items-inside-div-in-a-repeater SelectMany, Contains - http://stackoverflow.com/questions/11778979/better-code-pattern-for-checking-existence-of-value Enumerable.Range - http://stackoverflow.com/questions/11780128/scalable-c-sharp-code-for-creating-array-from-config-file WHERE http://stackoverflow.com/questions/13171850/trim-string-if-a-string-ends-with-a-specific-word What factors to take into account when deciding between LINQ and regular .Net language elements?

    Read the article

  • What is the most effective order to learn SQL Server, LINQ, and Entity Framework?

    - by user1525474
    I am trying to get some advice on what order I should learn about SQL Server, LINQ, and Entity Framework to be able to better work with ASP.NET Webforms and MVC. From what I've been able to learn so far, many recommend learning LINQ or Entity Framework before learning SQL Server. It also appears that many companies are looking for people with knowledge in LINQ-to-SQL and Entity Framework without mentioning SQL Server. However, my understanding is that LINQ-to-SQL and Entity Framework translate code into SQL Server queries, making this a poor approach. Is there a correct or best order in which to learn these technologies?

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >