Search Results

Search found 9232 results on 370 pages for 'linq tutorial'.

Page 33/370 | < Previous Page | 29 30 31 32 33 34 35 36 37 38 39 40  | Next Page >

  • Manual (Dynamic) LINQ subquery using IN clause

    - by immortalali-msn-com
    Hi Everyone, I want to query the DB through LINQ writing manual SQL, my linq method is: var q = db.TableView.Where(sqlAfterWhere); returnValue = q.Count(); this method queries well if the value passed to variable "sqlAfterWhere" is: (this variable is String type) it.Name = 'xyz' but what if i want to use IN clause, using a sub query. (i need to use 'it' before every column name in the above query to work), i cant use 'it' before the sub query columns as its a separate query, so what should i do, if i dont use any thing, and use column names directly it gives error saying " could not be resolved" where is my column names with out 'it' at the begining. So the query not working is: (this is a string passed to the variable above): it.Name IN (SELECT Name FROM TableName WHERE Address LIKE '%SomeAddress%') the errors come out as: Name could not be resolved Address could not be resolved The exact error is: "'Name' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly., near simple identifier, line 6, column 25." Same error for "Address as well if i use 'it.' before these columns it gives error as: "The element type 'Edm.Int32' and the CollectionType 'Transient.collection[Transient.rowtype(GroupID,Edm.Int32(Nullable=True,DefaultValue=))]' are not compatible. The IN expression only supports entity, primitive, and reference types. , near WHERE predicate, line 6, column 14." Thanks for the help

    Read the article

  • LINQ - IEnumerable.Join on Anonymous Result Set in VB.NET

    - by user337501
    I've long since built a way around this, but it still keeps bugging me... it doesnt help that my grasp of dynamic LINQ queries is still shakey. For the example: Parent has fields (ParentKey, ParentField) Child has fields (ChildKey, ParentKey, ChildField) Pet has fields (PetKey, ChildKey, PetField) Child has a foreign key reference to Parent on Child.ParentKey = Parent.ParentKey Pet has a foreign key reference to Child on Pet.Childkey = Child.ChildKey Simple enough eh? Lets say I have LINQ like this... Dim Q = FROM p in DataContext.Parent _ Join c In DataContext.Child On c.ParentKey = p.ParentKey Consider this a "base query" on which I will perform other filtering actions. Now I want to join the Pet table like this: Q = Q.Join(DataContext.Pet, _ Function(a) a.c.ChildKey, _ Function(p As Pet) p.ChildKey, _ Function(a, p As Pet) p.ChildKey = a.c.ChildKey) The above Join call doesnt work. I sort of understand why it doesnt work, but hopefully it'll show you how I tried to accomplish this task. After all this was done I would have appended a Select to finish the job. Any ideas on a better way to do this? I tried it with the PredicateBuilder with little success. I might not know how to use it right but it felt like it wasnt gonna handle the joining.

    Read the article

  • LINQ To SQL ignore unique constraint exception and continue

    - by Martin
    I have a single table in a database called Users Users ------ ID (PK, Identity) Username (Unique Index) I have setup a unique index on the Username table to prevent duplicates. I am then enumerating through a collection and creating a new user in the database for each item. What I want to do is just insert a new user and ignore the exception if the unique key constraint is violated (as it's clearly a duplicate record in that case). This is to avoid having to craft where not exists kind of queries. First off, is this going to be any more efficient or should my insert code be checking for duplicates instead? I'm drawn more to the database having that logic as this prevents any other type of client from inserting duplicate data. My other issue is related to LINQ To SQL. I have the following code: public class TestRepo { DatabaseDataContext database = new DatabaseDataContext(); public void Add(string username) { database.Users.InsertOnSubmit(new User() { Username = username }); } public void Save() { database.SubmitChanges(); } } And then I iterate over a collection and insert new users, ignoring any exceptions: TestRepo repo = new TestRepo(); foreach (var name in new string[] { "Tim", "Bob", "John" }) { try { repo.Add(name); repo.Save(); } catch { } } The first time this is run, great I have three users in the table. If I remove the second one and run this code again, nothing is inserted. I expected the first insert to fail with the exception, the second to succeed (as I just removed that item from the DB) and the third to then fail. What seems to be happening is that once the SqlException is thrown (even though the loop continues to iterate) all of the next inserts fail - even when there isn't a row in the table that would cause a unique violation. Can anyone explain this? P.S. The only workaround I could find was to instantiate the repo each time before the insert, then it worked exactly as excepted - indicating that it's something to do with the LINQ To SQL DataContext. Thanks.

    Read the article

  • Linq-to-Sql IIS7 Login failed for user ‘DOMAIN\MACHINENAME$’

    - by cfdev9
    I am encountering unexpected behaviour using Linq-to-sql DataContext. When I run my application locally it works as expected however after deploying to a test server which runs IIS7, I get an error Login failed for user ‘DOMAIN\MACHINENAME$’ when attempting to open objects from the DataContext. This code explains the error, which breaks on the very last line with the error "System.Data.SqlClient.SqlException: Login failed for user". var connStr ="Data Source=server;Initial Catalog=Test;User Id=testuser;Password=password"; //Test 1 var conn1 = new System.Data.SqlClient.SqlConnection(connStr); var cmdString = "SELECT COUNT(*) FROM Table1"; var cmd = new System.Data.SqlClient.SqlCommand(cmdString, conn1); conn1.Open(); var count1 = cmd.ExecuteScalar(); conn1.Close(); //Test 2 var conn2 = new System.Data.SqlClient.SqlConnection(connStr); var context = new TestDataContext(conn2); var count2 = context.Table1s.Count(); The connection string is not even using integrated security, so why is Linq-to-sql trying to connect as a specific user? If I change the server name in the connection string I get a different error so its using atleast part of the connection string, but apparently ignoring the UserId and Password. Very confused.

    Read the article

  • Linq-To-Objects group by

    - by Oskar Kjellin
    Hey, I'm building a software for timereporting I have a Dictionary<string, Dictionary<string, double>>. The key in the main dictionary is a users name and their value is a dictionary of . I have a function GetDepartment(string UserName) which returns a string with the users department. What I want is to crate a new dictionary, of the same type, that has the department as the main key and in the subdictionary a where hours is the total for that department. I have been trying to do this with linq but did not succeed. Would be very glad for some help here! EDIT: This code does exactly what I want. But I want it in LINQ Dictionary<string, Dictionary<string, double>> temphours = new Dictionary<string, Dictionary<string, double>>(); ; foreach (var user in hours) { string department = GetDepartment(user.Key); if (!temphours.ContainsKey(department)) { temphours.Add(department, new Dictionary<string, double>()); } foreach (var customerReport in user.Value) { if (!temphours[department].ContainsKey(customerReport.Key)) { temphours[department].Add(customerReport.Key, 0); } temphours[department][customerReport.Key] += customerReport.Value; } }

    Read the article

  • C# Linq List Contains Similar Elements

    - by John Peters
    Hi All, I am looking for linq query to see if there exists a similar object I have an object graph as follows Cart myCart = new Cart { List<CartProduct> myCartProduct = new List<CartProduct> { CartProduct cartProduct1 = new CartProduct { List<CartProductAttribute> a = new List<CartProductAttribute> { CartProductAttribute cpa1 = new CartProductAttribute{ title="red" }, CartProductAttribute cpa2 = new CartProductAttribute{ title="small" } } } CartProduct cartProduct2 = new CartProduct { List<CartProductAttribute> d = new List<CartProductAttribute> { CartProductAttribute cpa3 = new CartProductAttribute{ title="john" }, CartProductAttribute cpa4 = new CartProductAttribute{ title="mary" } } } } } I would like to get from the Cart = a CartProduct that has the exact same CartProductAttribute title values as a CartProduct that I need to compare. No more and no less. E.G. I need to find a similar CartProduct that has a CartProductAttribute with title="red" and a cartProductAttribute with title="small" in myCart (eg 'cartProduct1' in the example) CartProduct cartProductToCompare = new CartProduct { List<CartProductAttribute> cartProductToCompareAttributes = new List<CartProductAttribute> { CartProductAttribute cpa5 = new CartProductAttribute{ title="red" }, CartProductAttribute cpa6 = new CartProductAttribute{ title="small" } } } So from object graph myCart cartProduct1 cpa1 (title=red) cpa2 (title=small) cartProduct2 cpa3 (title=john) cpa4 (title=mary) Linq query looking for cartProductToCompare cpa5 (title=red) cpa6 (title=small) Should find cartProduct1 Hope all this makes sense... Thanks

    Read the article

  • Cannot update a single field using Linq to Sql

    - by KallDrexx
    I am having a hard time attempting to update a single field without having to retrieve the whole record prior to saving. For example, in my web application I have an in place editor for the Name and Description fields of an object. Once you edit either field, it sends the new field (with the object's ID value) to the web server. What I want is the webserver to take that value and ID and only update the one field. There are only two ways google tells me to do this: 1) When I get the value I want to change, the value and the ID, retrieve the record from the database, update the field in the c# object, and then send it back to the server. I don't like this method because not only does it include a completely unnecessary database read call (which includes two tables due to the way my schema is). 2) Set UpdateCheck for all the fields (but the primary keys) to UpdateCheck.Never. This doesn't work for me (I think) due to my mapping layer between the Linq to Sql and my Entity/ViewModel layer. When I convert my entity into the linq to sql db object it seems to be updating those fields regardless of the UpdateCheck setting. This might be just because of integers, since not setting an int means it is a zero (and no, I can't use int? instead). Are there any other options that I have?

    Read the article

  • SelectMany in Linq to entity

    - by Brazeta
    I was looking at some examples in microsoft site about linq and I see an example that I need to modify! http://msdn.microsoft.com/en-us/vcsharp/aa336758.aspx#SelectManyCompoundfrom3 public void Linq16() { List customers = GetCustomerList(); var orders = from c in customers from o in c.Orders where o.OrderDate >= new DateTime(1998, 1, 1) select new { c.CustomerID, o.OrderID, o.OrderDate }; ObjectDumper.Write(orders); } Insted of having a select that retrives the CustomerID, OrderID and OrderDate I want to select the CustomerID and a System.Collection.Generic.List that contains all the orders for that user! Essentially I want to group my orders by CustomerID, but i noticed that linq to entity does not allow a .ToList(object) inside the select. I want something like this... List customers = GetCustomerList(); var orders = from c in customers from o in c.Orders where o.OrderDate >= new DateTime(1998, 1, 1) select new xpto { TheCostumerID = c.CustomerID, CostumerOrders = o.Select(i=>i.OrderID).ToList(), }; ...but the .ToList() is a big problem, at least for me. I'm trying to find out the solution for that but so far I have acomplished nothing! Please help me.

    Read the article

  • Help Converting T-SQL Query to LINQ Query

    - by campbelt
    I am new to LINQ, and so am struggle over some queries that I'm sure are pretty simple. In any case, I have been hiting my head against this for a while, but I'm stumped. Can anyone here help me convert this T-SQL query into a LINQ query? Once I see how it is done, I'm sure I'll have some question about the syntax: SELECT BlogTitle FROM Blogs b JOIN BlogComments bc ON b.BlogID = bc.BlogID WHERE b.Deleted = 0 AND b.Draft = 0 AND b.[Default] = 0 AND bc.Deleted = 0 GROUP BY BlogTitle ORDER BY MAX([bc].[Timestamp]) DESC Just to show that I have tried to solve this on my own, here is what I've come up with so far, though it doesn't compile, let alone work ... var iqueryable = from blog in db.Blogs join blogComment in db.BlogComments on blog.BlogID equals blogComment.BlogID where blog.Deleted == false && blog.Draft == false && blog.Default == false && blogComment.Deleted == false group blogComment by blog.BlogID into blogGroup orderby blogGroup.Max(blogComment => blogComment.Timestamp) select blogGroup;

    Read the article

  • populating object collection property with Linq

    - by Benjamin Ortuzar
    I have an XML structure that has many doc nodes, and each node may have zero or more extract paragraphs (paras). <doc> <docitem>3</docitem> <docid>129826</docid> <doctitle>sample title</doctitle> <docdatetime>2009-07-03T16:59:00</docdatetime> <collectdatetime>2009-07-03T16:59:23</collectdatetime> <summary> <summarytext>sample summary</summarytext> </summary> <paras> <paraitemcount>2</paraitemcount> <para> <paraitem>1</paraitem> <paratext>sample text 1</paratext> </para> <para> <paraitem>2</paraitem> <paratext>sample text 2</paratext> </para> </paras> </doc> <doc> ... </doc> I also has some Linq code to populate some Document objects: List<Document> documentsList = (from doc in xmlDocument.Descendants("doc") select new Document { DocId = doc.Element("docid").Value, DocTitle = doc.Element("doctitle").Value, DocDateTime = DateTime.Parse(doc.Element("docdate").Value), DocSummary = doc.Element("summary").Value, DocParas = "" ///missing code to populate List<string> } ).ToList<Document>(); Is it possible add all the paras nodes into the Document.DocParas List<string> using Linq and Xpath, or should I do this task in a different way? Note: I'm using .NET C# 3.5

    Read the article

  • Create System.Data.Linq.Table in Code for Testing

    - by S. DePouw
    I have an adapter class for Linq-to-Sql: public interface IAdapter : IDisposable { Table<Data.User> Activities { get; } } Data.User is an object defined by Linq-to-Sql pointing to the User table in persistence. The implementation for this is as follows: public class Adapter : IAdapter { private readonly SecretDataContext _context = new SecretDataContext(); public void Dispose() { _context.Dispose(); } public Table<Data.User> Users { get { return _context.Users; } } } This makes mocking the persistence layer easy in unit testing, as I can just return whatever collection of data I want for Users (Rhino.Mocks): Expect.Call(_adapter.Users).Return(users); The problem is that I cannot create the object 'users' since the constructors are not accessible and the class Table is sealed. One option I tried is to just make IAdapter return IEnumerable or IQueryable, but the problem there is that I then do not have access to the methods ITable provides (e.g. InsertOnSubmit()). Is there a way I can create the fake Table in the unit test scenario so that I may be a happy TDD developer?

    Read the article

  • Beginner LINQ to XML inline XML error

    - by Kyle B.
    Imports System.Xml.Linq Imports System.Linq Partial Class test2 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim xml As XElement = <book> <title>My Title</title> <author>Kyle</author> <publisher>WROX</publisher> </book> End Sub End Class The above code is producing the following error: Compiler Error Message: BC30201: Expression expected. Source Error: Line 8: Line 9: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Line 10: Dim xml As XElement = <book> Line 11: <title>My Title</title> Line 12: <author>Kyle</author> Source File: C:\Inetpub\wwwroot\myproject\web\test2.aspx.vb Line: 10 Why? edit: Dim xml As XElement = New XElement("book", _ New XElement("title", "My Title"), _ New XElement("author", "Kyle"), _ New XElement("publisher", "WROX") _ ) The above code works, but obviously is not as elegant as the original and I would still appreciate an explanation of why my original syntax is wrong.

    Read the article

  • Linq-To-Entities group by

    - by Oskar Kjellin
    Hey, I'm building a software for timereporting I have a Dictionary<string, Dictionary<string, double>>. The key in the main dictionary is a users name and their value is a dictionary of . I have a function GetDepartment(string UserName) which returns a string with the users department. What I want is to crate a new dictionary, of the same type, that has the department as the main key and in the subdictionary a where hours is the total for that department. I have been trying to do this with linq but did not succeed. Would be very glad for some help here! EDIT: This code does exactly what I want. But I want it in LINQ Dictionary<string, Dictionary<string, double>> temphours = new Dictionary<string, Dictionary<string, double>>(); ; foreach (var user in hours) { string department = GetDepartment(user.Key); if (!temphours.ContainsKey(department)) { temphours.Add(department, new Dictionary<string, double>()); } foreach (var customerReport in user.Value) { if (!temphours[department].ContainsKey(customerReport.Key)) { temphours[department].Add(customerReport.Key, 0); } temphours[department][customerReport.Key] += customerReport.Value; } }

    Read the article

  • Dynamic SQL To Dynamic LINQ in VB.NET with MS SQL Server 2008

    - by user337501
    I dread asking this question, because with what I've read so far I understand im gonna have to cram a lotta new things into my head. In spite of all the similiar questions(and the wide variety of answers) I thought I'd ask as nothing I've read tailors to what I need specifically enough. I need to represent the following query using LINQ: DECLARE @PurchasedInventoryItemID Int = 2 DECLARE @PurchasedInventorySectionID Int = 0 DECLARE @PurchasedInventoryItem_PurchasingCategoryID Int = 3 DECLARE @PurchasedInventorySection_PurchasingCategoryID Int = 0 DECLARE @IsActive Bit = 1 DECLARE @PropertyID Int = 2 DECLARE @PropertyValue nvarchar(1000) = 'Granny Smith' --Property1, Property2, Property3 ... SELECT O.PurchasedInventoryObjectID, O.PurchasedInventoryObjectName, O.PurchasedInventoryConjunctionID, O.Summary, O.Count, O.PropertyCount, O.IsActive FROM tblPurchasedInventoryObject As O INNER JOIN tblPurchasedInventoryConjunction As C ON C.PurchasedInventoryConjunctionID = O.PurchasedInventoryConjunctionID INNER JOIN tblPurchasedInventoryItem As I ON I.PurchasedInventoryItemID = C.PurchasedInventoryItemID INNER JOIN tblPurchasedInventorySection As S ON S.PurchasedInventorySectionID = C.PurchasedInventorySectionID INNER JOIN tblPurchasedInventoryPropertyMap as M ON M.PurchasedInventoryObjectID = O.PurchasedInventoryObjectID INNER JOIN tblPropertyValue As V ON V.PropertyValueID = M.PropertyValueID WHERE I.PurchasedInventoryItemID = @PurchasedInventoryItemID AND S.PurchasedInventorySectionID = @PurchasedInventorySectionID AND I.PurchasingCategoryID = @PurchasedInventoryItem_PurchasingCategoryID AND S.PurchasingCategoryID = @PurchasedInventorySection_PurchasingCategoryID AND O.IsActive = @IsActive AND V.PropertyID = @PropertyID AND V.Value = @PropertyValue Now, I know that a query in .NET doesnt look like this, this is my test in the SQL Design Studio. Naturally VB.NET variables will be used in place of the SQL local variables. My problem is this: All of the conditions after "WHERE" are optional. In that a query might be made that uses one, some, all, or none of the conditions. V.PropertyID and V.Value can also appear any number of times. In VB.NET I can make this query easy enough by simply concatenating strings, and using a loop to append the "V.PropertyID/V.Value" conditions. I can also make a Stored Procedure in MS SQL, which is easy enough. However, I want to accomplish this using LINQ. If anyone could direct me, I would be most appreciative.

    Read the article

  • Linq to SQL case sensitivity causing problems

    - by Roger Lipscombe
    I've seen this question, but that's asking for case-insensitive comparisons when the database is case-sensitive. I'm having a problem with the exact opposite. I'm using SQL Server 2005, my database collation is set to Latin1_General_CI_AS. I've got a table, "User", like this: CREATE TABLE [dbo].[User] ( [Id] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](max) NOT NULL, CONSTRAINT [PK_Example] PRIMARY KEY CLUSTERED ( [Id] ASC ) ) And I'm using the following code to populate it: string[] names = new[] { "Bob", "bob", "BoB" }; using (MyDataContext dataContext = new AppCompatDataContext()) { foreach (var name in names) { string s = name; if (dataContext.Users.SingleOrDefault(u => u.Name == s) == null) dataContext.Users.InsertOnSubmit(new User { Name = name }); } dataContext.SubmitChanges(); } When I run this the first time, I end up with "Bob", "bob" and "BoB" in the table. When I run it again, I get an InvalidOperationException: "Sequence contains more than one element", because the query against the database returns all 3 rows, and... SELECT * FROM [User] WHERE Name = 'bob' ... is case-insensitive. That is: when I'm inserting rows, Linq to SQL appears to use C# case-sensitive comparisons. When I query later, Linq to SQL uses SQL Server case-insensitive comparisons. I'd like the initial insert to use case-insensitive comparisons, but when I change the code as follows... if (dataContext.Users.SingleOrDefault(u => u.Name.Equals(s, StringComparison.InvariantCultureIgnoreCase) ) == null) ... I get a NotSupportedException: "Method 'Boolean Equals(System.String, System.StringComparison)' has no supported translation to SQL." Question: how do I get the initial insert to be case-insensitive or, more precisely, match the collation of the column in the database? Update: This doesn't appear to be my problem. My problem appears to be that SingleOrDefault doesn't actually look at the pending inserts at all.

    Read the article

  • LINQ Normalizing data

    - by Brennan Mann
    I am using an OMS that stores up to three line items per record in the database. Below is an example of an order containing five line items. Order Header Order Detail Prod 1 Prod 2 Prod 3 Order Detail Prod 4 Prod 5 One order header record and two detail records. My goal is have a one to one relation for details records(i.e., one detail record per line item). In the past, I used an UNION ALL SQL statement to extract the data. Is there a better approcach to this problem using LINQ? Below is my first attempt at using LINQ. Any feedback, suggestions or recommendations would greatly be appreciated. For what I have read, an UNION statement can tax the process? var orderdetail = (from o in context.ORDERSUBHEADs select new { edpNo = o.EDPNOS_001, price = o.EXTPRICES_001, qty = o.ITEMQTYS_001 } ).Union(from o in context.ORDERSUBHEADs select new { edpNo = o.EDPNOS_002, price = o.EXTPRICES_002, qty = o.ITEMQTYS_002 } ).Union(from o in context.ORDERSUBHEADs select new { edpNo = o.EDPNOS_003, price = o.EXTPRICES_003, qty = o.ITEMQTYS_003 });

    Read the article

  • Databinding question: DataGridView <=> XDocument (using LINQ-to-XML)

    - by Pretzel
    Learning LINQ has been a lot of fun so far, but despite reading a couple books and a bunch of online resources on the topic, I still feel like a total n00b. Recently, I just learned that if my query returns an Anonymous type, the DataGridView I'm populating will be ReadOnly (because, apparently Anonymous types are ReadOnly.) Right now, I'm trying to figure out the easiest way to: Get a subset of data from an XML file into a DataGridView, Allow the user to edit said data, Stick the changed data back into the XML file. So far I have Steps 1 and 2 figured out: public class Container { public string Id { get; set; } public string Barcode { get; set; } public float Quantity { get; set; } } // For use with the Distinct() operator public class ContainerComparer : IEqualityComparer<Container> { public bool Equals(Container x, Container y) { return x.Id == y.Id; } public int GetHashCode(Container obj) { return obj.Id.GetHashCode(); } } var barcodes = (from src in xmldoc.Descendants("Container") where src.Descendants().Count() > 0 select new Container { Id = (string)src.Element("Id"), Barcode = (string)src.Element("Barcode"), Quantity = float.Parse((string)src.Element("Quantity").Attribute("value")) }).Distinct(new ContainerComparer()); dataGridView1.DataSource = barcodes.ToList(); This works great at getting the data I want from the XML into the DataGridView so that the user has a way to manipulate the values. Upon doing a Step-thru trace of my code, I'm finding that the changes to the values made in DataGridView are not bound to the XDocument object and as such, do not propagate back. How do we take care of Step 3? (getting the data back to the XML) Is it possible to Bind the XML directly to the DataGridView? Or do I have to write another LINQ statement to get the data from the DGV back to the XDocument? Suggstions?

    Read the article

  • LINQ Query to DataTable.DataSource

    - by lumberjack
    I am trying to perform a LINQ query on a DataTable and show the result in another DataTable. My source DataTable looks something like this: DataTable myDataTable = new DataTable(); myDataTable.Columns.Add("OrderID", typeof(int)); myDataTable.Columns.Add("Date", typeof(DateTime)); myDataTable.Columns.Add("UnitsPurchased", typeof(int)); The resulting DataTable looks like this when filled: Order ID Date Units Purchased 16548 10/15/09 250 17984 11/03/09 512 20349 01/11/10 213 34872 01/15/10 175 My current LINQ query looks like this: IEnumerable<DataRow> query = (from row in myDataTable.AsEnumerable() where row.UnitsPurchased > 200 select new { row.OrderID, row.Date, row.UnitsPurchased }) as IEnumerable<DataRow>; resultDataTable.DataSource = query.CopyToDataTable<DataRow>(); Every time I run this code query is null. I can see that that the as IEnumerable<DataRow> is the culprit, but it makes no since to me since DataTable.AsEnumerable() returns an IEnumerable<DataRow>. Any help would be appreciated.

    Read the article

  • Dynamic Linq Property Converting to Sql

    - by Matthew Hood
    I am trying to understand dynamic linq and expression trees. Very basically trying to do an equals supplying the column and value as strings. Here is what I have so far private IQueryable<tblTest> filterTest(string column, string value) { TestDataContext db = new TestDataContext(); // The IQueryable data to query. IQueryable<tblTest> queryableData = db.tblTests.AsQueryable(); // Compose the expression tree that represents the parameter to the predicate. ParameterExpression pe = Expression.Parameter(typeof(tblTest), "item"); Expression left = Expression.Property(pe, column); Expression right = Expression.Constant(value); Expression e1 = Expression.Equal(left, right); MethodCallExpression whereCallExpression = Expression.Call( typeof(Queryable), "Where", new Type[] { queryableData.ElementType }, queryableData.Expression, Expression.Lambda<Func<tblTest, bool>>(e1, new ParameterExpression[] { pe })); // Create an executable query from the expression tree. IQueryable<tblTest> results = queryableData.Provider.CreateQuery<tblTest>(whereCallExpression); return results; } That works fine for columns in the DB. But fails for properties in my code eg public partial class tblTest { public string name_test { get { return name; } } } Giving an error cannot be that it cannot be converted into SQL. I have tried rewriting the property as a Expression<Func but with no luck, how can I convert simple properties so they can be used with linq in this dynamic way? Many Thanks

    Read the article

  • List Manipulation in C# using Linq

    - by Learner
    using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace ConsoleApplication1 { public class Class1 { static void Main(string[] args) { List<Car> mylist = new List<Car>(); Car car1; Car car2; Car car3; car1 = new Car() { make = "Honda", id = 1 }; car2 = new Car() { make = "toyota", id = 2 }; car3 = new Car() { make = "Honda", id = 3, color = "red" }; mylist.Add(car1); mylist.Add(car2); **////mylist.Where(p => p.id == 1).SingleOrDefault() = car3;** } } public class Car { public int id { get; set; } public string make { get; set; } public string color { get; set; } } } How can I update the list by replacing the honda car of Id 1 with honda car with Id 3 in the best way.

    Read the article

  • Creating LINQ to SQL Data Models' Data Contexts with ASP.NET MVC

    - by Maxim Z.
    I'm just getting started with ASP.NET MVC, mostly by reading ScottGu's tutorial. To create my database connections, I followed the steps he outlined, which were to create a LINQ-to-SQL dbml model, add in the database tables through the Server Explorer, and finally to create a DataContext class. That last part is the part I'm stuck on. In this class, I'm trying to create methods that work around the exposed data. Following the example in the tutorial, I created this: using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MySite.Models { public partial class MyDataContext { public List<Post> GetPosts() { return Posts.ToList(); } public Post GetPostById(int id) { return Posts.Single(p => p.ID == id); } } } As you can see, I'm trying to use my Post data table. However, it doesn't recognize the "Posts" part of my code. What am I doing wrong? I have a feeling that my problem is related to my not adding the data tables correctly, but I'm not sure. Thanks in advance.

    Read the article

  • Linq join two dictionaries using a common key

    - by rboarman
    Hello, I am trying to join two Dictionary collections together based on a common lookup value. var idList = new Dictionary<int, int>(); idList.Add(1, 1); idList.Add(3, 3); idList.Add(5, 5); var lookupList = new Dictionary<int, int>(); lookupList.Add(1, 1000); lookupList.Add(2, 1001); lookupList.Add(3, 1002); lookupList.Add(4, 1003); lookupList.Add(5, 1004); lookupList.Add(6, 1005); lookupList.Add(7, 1006); // Something like this: var q = from id in idList.Keys join entry in lookupList on entry.Key equals id select entry.Value; The Linq statement above is only an example and does not compile. For each entry in the idList, pull the value from the lookupList based on matching Keys. The result should be a list of Values from lookupList (1000, 1002, 1004). What’s the easiest way to do this using Linq? Thank you, Rick

    Read the article

  • Sending items in a LINQ sequence to a method that returns void

    - by generalt
    Hello all. Often while I'm dealing with LINQ sequences, I want to send each item to a method returning void, avoiding a foreach loop. However, I haven't found an elegant way to do this. Today, I wrote the following code: private StreamWriter _sw; private void streamToFile(List<ErrorEntry> errors) { if (_sw == null) { _sw = new StreamWriter(Path.Combine (Path.GetDirectoryName(_targetDatabasePath), "errors.txt")); } Func<ErrorEntry, bool> writeSelector = (e) => { _sw.WriteLine(getTabDelimititedLine(e)); return true; }; errors.Select(writeSelector); _sw.Flush(); } As you can see, I write a lambda function that just returns true, and I realize that the Select method will return a sequence of booleans- I'll just ignore that sequence. However, this seems a little bit noobish and jank. Is there any elegant way to do this? Or am I just misapplying LINQ? Thanks.

    Read the article

  • Sort a List<T> using query expressions - LINQ C#

    - by Dan Yack
    I have a problem using Linq to order a structure like this : public class Person { public int ID { get; set; } public List<PersonAttribute> Attributes { get; set; } } public class PersonAttribute { public int ID { get; set; } public string Name { get; set; } public string Value { get; set; } } A person might go like this: PersonAttribute Age = new PersonAttribute { ID = 8, Name = "Age", Value = "32" }; PersonAttribute FirstName = new PersonAttribute { ID = 9, Name = "FirstName", Value = "Rebecca" }; PersonAttribute LastName = new PersonAttribute { ID = 10, Name = "LastName", Value = "Johnson" }; PersonAttribute Gender = new PersonAttribute { ID = 11, Name = "Gender", Value = "Female" }; I would like to use LINQ projection to sort a list of persons ascending by the person attribute of my choice, for example, sort on Age, or sort on FirstName. I am trying something like string mySortAttribute = "Age" PersonList.OrderBy(p => p.PersonAttribute.Find(s => s.Name == mySortAttribute).Value); But the syntax is failing me. Any clues? Thanks in advance!

    Read the article

  • How do I setup Linq to SQL and WCF

    - by Jisaak
    So I'm venturing out into the world of Linq and WCF web services and I can't seem to make the magic happen. I have a VERY basic WCF web service going and I can get my old SqlConnection calls to work and return a DataSet. But I can't/don't know how to get the Linq to SQL queries to work. I'm guessing it might be a permissions problem since I need to connect to the SQL Database with a specific set of credentials but I don't know how I can test if that is the issue. I've tried using both of these connection strings and neither seem to give me a different result. <add name="GeoDataConnectionString" connectionString="Data Source=SQLSERVER;Initial Catalog=GeoData;Integrated Security=True" providerName="System.Data.SqlClient" /> <add name="GeoDataConnectionString" connectionString="Data Source=SQLSERVER;Initial Catalog=GeoData;User ID=domain\userName; Password=blahblah; Trusted_Connection=true" providerName="System.Data.SqlClient" /> Here is the function in my service that does the query and I have the interface add the [OperationContract] public string GetCity(int cityId) { GeoDataContext db = new GeoDataContext(); var city = from c in db.Cities where c.CITY_ID == 30429 select c.DESCRIPTION; return city.ToString(); } The GeoData.dbml only has one simple table in it with a list of city id's and city names. I have also changed the "Serialization Mode" on the DataContext to "Unidirectional" which from what I've read needs to be done for WCF. When I run the service I get this as the return: SELECT [t0].[DESCRIPTION] FROM [dbo].[Cities] AS [t0] WHERE [t0].[CITY_ID] = @p0 Dang, so as I'm writing this I realize that maybe my query is all messed up?

    Read the article

< Previous Page | 29 30 31 32 33 34 35 36 37 38 39 40  | Next Page >