|
|
January 2008 - Posts
-
To whom it may concern: Could anyone tell me how to convert the code written in 2006 May CTP to LINQ 3.5? ParameterExpression parameterExpression = Expression .Parameter( typeof (T), null ); LambdaExpression lambda = QueryExpression.Lambda( "Deleted==False" , new ParameterExpression [] { parameterExpression }); IQueryable sequence = sequence.CreateQuery(QueryExpression.Where(sequence.Expression, lambda)); I understand we might need sth like: Expression expression = Expression .Call( typeof ( Queryable Read More...
|
-
I have the following 3 table structures in my database. Affiliate AffiliateAddress Address [affiliateid] [affiliateid] [addressid] [affiliatename] [addressid] [street1] [weburl] [street2] ..... So as you can see, AffiliateAddress is an associative table that maps an address record to an affiliate record. I have been able to insert a new record into the affiliate and address tables and also update existing ones. What I can't figure out how to do is insert/update an affiliate and add an address while Read More...
|
-
I have added two additional properties like sum, average by Creating a Partial Class. In my sql statement I am returing sum, average. Now when I retrive record by DLINQ I am not getting those value in my sum,average properties. So how can I get this value into my properties? Thanks, Rezwan Read More...
|
-
Code Snippet Partial Class LinkExtractorDataContext Public Function GetSites() As SiteCollection Dim lst = New SiteCollection For Each site In Me .tblSites Dim objSite = New SiteEntity() With objSite .SiteID = site.SiteID .Name = site.Name .URL = site.URL .Description = site.Description .DateAdded = site.DateAdded 'add all Link rows from lookup table for this site. Dim lnks = From lnk In Me .tblLinks _ Join SiteLinks In site.tblSiteLink_Lookups _ On lnk.LinkID Equals SiteLinks.LinkID _ Select lnk Read More...
|
-
Hello, and thanks in advance. I've created a database view and I'd like to query it using Linq. I'm fairly inexperienced with Linq, so I may be overlooking something easy. I have a string array of possible identifiers for these rows - but which identifer to use is selected at runtime - something like Id, Name, SerialNumber I have two parameters - the name of the property to query, and the String[] of identifiers. I want to say something like: Type t = db.ConnectionStatus.GetType(); PropertyInfo identifierProperty= Read More...
|
-
I'm learning LINQ and I get an error on line below. Any advice on how to fix? dpcontacts.dpcontacts.Remove(myContacts); Error msg-Cannot remove an enity that has not been attached. Exception below: System.InvalidOperationException was unhandled Message=" Cannot remove an entity that has not been attached ." Source="System.Data.Linq" StackTrace: at System.Data.Linq.Table`1.Remove(TEntity entity) at Dpcontacts.Form1.delete_Click_1(Object sender, EventArgs e) in C:\Users\Ron\Documents\Visual Studio Read More...
|
-
Normally the C# compiler returns warning CS0665 for the common typo of using an assignment = (instead of a comparison == ) in places where a boolean type is expected (e.g. inside an if statement). http://msdn2.microsoft.com/en-us/library/c1sde1ax.aspx But this warning is not emitted when you use an assignment inside a LINQ where clause. Here's a code snippet showing the problem. Is this a C# bug or intended behavior? Code Snippet class Foo { public bool IsTrue { get ; set ; } void test() { List Foo Read More...
|
-
My table structure is: Orders->Notes My Window binds to an Order Entity and has a listbox that binds to an IOrderedEnumerable Notes. (Basically I'm just sorting the notes in descending order. When I force a conflict on the Notes table no error is thrown. This catches conflicts on the Order table, but not on Notes: Code Snippet try { _Db.SubmitChanges( ConflictMode .ContinueOnConflict); } catch ( ChangeConflictException exc) try { db.SubmitChanges( ConflictMode .ContinueOnConflict); } catch ( ChangeConflictException Read More...
|
-
Hello, The LINQ-to-SQL classes designer makes use of settings where the connection string is stored, as well as the configuration file that has the connection string. When changing the connection string, the setting file doesn't suck this in automatically; rather a prompt pops up with the new connection string. So what is the offical way to change the location of the server when deploying an application? Do you edit both the connection string and the settings file manually? What do you do? Thanks Read More...
|
-
I have a vb.net 2005 project that I upgraded to 2008, I want to add the Linq to Sql Class but it doesn't show up when I go to Add -> New Item like it does in a project that was created in 2008, How do I add the class to my upgraded project? Thanks Read More...
|
-
I'm starting to compile a list of answers to common questions people have with LINQ to SQL that I hope will help dispell misconceptions people have with how to use it. This is what I've got so far... Q: How do I get default values from the database when inserting new entities? A: LINQ to SQL does not support using default values from the database. The values in the entity at the time SubmitChanges is called are used instead. You can override how LINQ to SQL inserts entities by implementing an insert Read More...
|
-
helow im jast starting to work with linkq . im tring to write linkq sentence that will give me all the string values from an array of classs that contains a Generic list of the string . for example : public class ClsCommand { public List string > words; } public List ClsCommand > Commands ; ... var all_words = ????? i what to get all the strings Read More...
|
-
I tried to convert to vb.net the linq and I got an error. Tell me please what is wrong. public static List Tag > GetPopularTags( int pageSize) { List Tag > result = new List Tag >(); using ( VideoShowDataContext dc = new VideoShowDataContext (ConnectionString)) { var popularTags = ( from vtt in dc.VideosToTags join t in dc.Tags on vtt.TagId equals t.TagId group vtt by vtt.TagId into topTags orderby topTags.Count() descending select new { tagId = topTags.Key, tagName = ( from tag in dc.Tags where Read More...
|
-
Hi, Consider that I have an already built Typed DataSet with multiple related tables. Accross the application, the same structure is used. My questions are -- 1. Where and Why should I use LINQ in this design ? 2. Whether there are any performance benefits for using LINQ to DataSet or LINQ to SQL ? 3. Can LINQ to SQL replace the traditional Data Access Layer completly ? 4. Is there any facility in LINQ to keep Relations (between data tables) in mind when giving result of a query ? Means if a Master Read More...
|
-
hi! I am new to LINQ, can anybody tell me how can i update multiple records using LINQ without having to iterating using loop. DataClassesDataContext ds = new DataClassesDataContext (); var employees = ds.Employees.Where(em => em.City.StartsWith( "B" )); foreach ( var emp in employees) { emp.City = "ABC" ; } ds.SubmitChanges(); Thanks. Read More...
|
-
I have very little experience using xml, and have really been fighting through this, so I hope someone can help me out. I have defined classes Part, Order, OrderLineItem.... Code Snippet public class Part { public string PartNumber { get; set; } public string Description { get; set; } public string Category { get; set; } } public class OrderLineItem { public int Quantity { get; set; } public Part Part { get; set; } } public class Order { public Guid OrderId { get; set; } public string JobNumber { Read More...
|
-
I’m working in VS2008 using LINQ-to-SQL and have bound fields to a windows form. I can update the field values manually, navigate to another record, navigate back to the record and the field value change sticks. However when I update a field value programmatically (i.e. I change the value in Textbox1.Text for example). The value change doesn’t stick when I navigate away to and come back to that record. I have a field that I need to calculate and populate programatically but that same field can be Read More...
|
-
I can see where Delete, Insert and Update are used. But when is None typically used? Read More...
|
-
Hello, I have a request for assistance. I am trying to join elements in my xml doc to get associate colors to highlight a state on a map. Essentially it is laid out like this... Code Snippet 255 0 0 So as you can see what I am trying to do is join the colors/color/attribute "ref" with states/state/attribute id this is what i have as my statement so far... Code Snippet join sC in stateColors.Elements("Info").Elements("States").Elements("State") on state.RegionName equals sC.Attribute("name").Value Read More...
|
-
I've been having a problem with LINQ for a while, and that is the behavior of default column values. If you have a table defined to have a "DEFAULT" value, the database is supposed to insert the default value when the column is omitted from the specified column list. e.g., CREATE TABLE [dbo] . [ABC] ( [Name] [nvarchar] ( 25 ) NOT NULL, [IDNumber] INT DEFAULT(10) NOT NULL ) Under SQL, an operation like this: INSERT INTO ABC(Name, IDNumber) VALUES ('Jim', 22); will produce a row with values 'Jim', Read More...
|
-
Hi All, I have a DataTable that contains Agent Data. An example of what the table looks like: ---------------------------------------- Agent Group Duration Matt 1 25 Matt 1 30 Matt 2 10 Bill 1 30 Bill 1 20 ----------------------------------------- What I want to do is write a LINQ command to group the data on Agent and Group, while summing the Duration, so that my return set would look something like: ---------------------------------------- Agent Group Duration Matt 1 55 Matt 2 10 Bill 1 50 ---------------------------------------- Read More...
|
-
Another bug in samples . How to correct this query ? Code Snippet var orders = from c in customers, o in c.Orders, total = o.Total where total >= 2000.0M select new {c.CustomerID, o.OrderID, total}; I get "A query must end with the select clause or a group clause. Thanks! Read More...
|
-
Hello, I am doing a asp.net webservice project and want to use linq to invoke the stored procedure in the database. Also, I want the return value to be a DataSet. Can I convert the linq query result to a DataSet object? Thanks. Read More...
|
-
I have problem with concenation of columns in different collations : Dim query= From r In Table _ Select c = r.Column1 & " " & r.Column2 where Column1 and Column2 is different in collation .Thus when query executed, i get Cannot resolve collation conflict for column 1 in SELECT statement. error.How can i handle this situtation in linq and also in dynamic linq?Thanks.. Read More...
|
-
Hi there, I need to write a simple application to modify our corporate database. I made up this query: Code Snippet Dim InterneWerkstattNr = From WerkstattAuftrag In db.WerkstattAuftrags _ Where WerkstattAuftrag.Werkstattauftragsnummer = TextBox1.Text.ToString _ Select WerkstattAuftrag.InterneWerkstattnummer It should get the the 'InterneWerkstattNr' associated with the 'Werkstattauftragsnummer' which is chosen by the user in TextBox1. So far, so good. Now I need to display the 'InterneWerkstattNr' Read More...
|
-
I noticed that when I do update and call SubmitChanges, the SQL statment contains where conditions with all the columns. Is there a way to limit that with just the primary key ? Thanks Read More...
|
-
I have the following code. What it should do is get workorders for an employee from two different tables. It needs the second table to lookup the name of the customer. The Employee's name of all results must be the one specified in combobox1. CODE Dim CustomJobs = From Jobs In db.Workorders _ From Customers In db.Customers _ Order By Jobs.Priority _ Order By Jobs.DateReceived Ascending _ Where Jobs.Employee = combobox1.text _ Select Jobs.ProblemDescription, Customers.CustomerName frmJobs.WorkorderBindingSource.DataSource Read More...
|
-
Hi everyone, I'm pretty new to LINQ and I've run across a problem that I can't seem to fix myself. I have a working SQL query that looks like this: Code Snippet SELECT COUNT ( dbo . PDI . coilId ) AS NumberOfCoils, ROUND ( SUM ( dbo . GagTrends . coilLength ), 0 ) AS TotalLength FROM dbo . PcProcStat INNER JOIN dbo . PDI ON dbo . PcProcStat . cid = dbo . PDI . cid INNER JOIN dbo . GagTrends ON dbo . PDI . cid = dbo . GagTrends . cid WHERE ( dbo . PcProcStat . trMndClpsd_time BETWEEN @DateStart AND Read More...
|
-
Our application is under source control (TFS if it matters), and everytime any developer opens a LINQ DBML file, VS tries to check out the project (VBPROJ) file. The DBML code-behind file has already been generated and added to the project, then subsequently checked back in, so that's not the cause. Simply cancelling the check-out request works, and the DBML file opens without any errors and can be checked out and worked on after that, but it does get rather annoying having to cancel the project Read More...
|
-
Hello, how to corret this sample code? Code Snippet ... int [] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int [] numbersB = { 1, 3, 5, 7, 8 }; var pairs = from a in numbersA, b in numbersB where a select new {a, b}; ... I get "A query body must end with a select clause or a group" error. Thanks! Read More...
|
-
1) Is there an east\y way to set all the columns to UpdateCheck.Never programtically / 2) Assuming that I use NorthWind Sample database and that I have the following predicate Expression> predicate = c => c.City == "London"; and that I call a function fool (predicate) is there a way to find out the dataContext of this predicate ? Read More...
|
-
Hi All, Just after a little advice with passing data. I have a 3 layered app with 1 of the layers consisting of a DAL. Here i have LINQ query which queries a SQL database on a server. Before i moved to LINQ i was using data adapters and filling the results of an SQL query into a dataset, which i was able to return to the correct layer. My question is how do i do this using LINQ and is this the best method of passing my query results. My current code uses the var keyword and this is what i need to Read More...
|
-
I written query, "find all records having number >1 but different Catalog values": var query = from b in db.GroupCountTests group new { b.Code, b.Catalog } by b.Code into g where g.Distinct().Count() > 1 select g; It works, but for each group access, round-trip to database occurs, what is big penalty to performance, first SQL getting groups, and then SQL queries separately getting content for each group. how to write such a query, that makes only one SQL query ? thanks Read More...
|
-
How much longer will we have to write object.Equals(a, b) when using Linq-to-SQL? The rest of the Linq data providers understand that in the C# language, null == null . Will the SQL provider be joining them at some point? If I wanted null values treated as a special case, I'd use a language called "SQL". If I wanted to write awful code like object.Equals(device.Id, targetId) instead of device.Id == targetId ...I'd use a language called "LISP". Read More...
|
-
When inserting a single record in one specific table in my app, I get an indexoutofrange exception. Does anyone have any idea what may cause this exception? There is nothing unusual with the table so I don't understand why I would get this exception. Code: SomeTable tbl = new SomeTable(); tbl.ID = Guid.NewGuid(); tbl.field1 = "somevalue"; tbl.field2 = "somevalue"; tbl.field3 = "somevalue"; //insert into the db using (SomeDataContext dc = new SomeDataContext()) { //transaction dc.SomeTables.InsertOnSubmit(tbl) Read More...
|
-
Hi, I'm pretty new to LINQ and am having some problems getting my DataRows to update based on the result of a LINQ query. I have a table, called RawData, with a column called DemoCode. I need these to update based on the criteria I supply in the where clause. So far I have the code below, just need that extra step to get there! Code Snippet DataAccess. RawDataDS ds = DataAccess. RawDataDSManagement .RawData; DataTable rawData = ds.Tables[ "RawData" ]; IEnumerable DataRow > lstRawData = ( from row Read More...
|
-
There is likely a better way to do this but I am wanting to bind a dropdown list to a LINQ to SQL query and yet insert one row to the top containing text such as "[Select Category]" and a value of "" or 0. I know I can do this but setting the DataSource to nothing and doing [DropDown].Items.Insert(0, New ListItem("[Select Category]", "0")) but I want to have it so the datasource itself has the additional data. It looks like it might be possible to do something using the .concat operator to append Read More...
|
-
Hi, I am trying to exclude the 3 rd element from my array. At this point I use the following code: string[] f = { "A", "B", "C","D","E" }; int idx = 2; string[] r = f.Take(idx).Union(f.Skip(idx+1)).ToArray(); Is there any better way to do this? Thank you, Max Read More...
|
-
Hi, I am trying to insert a none unicode value to the database using LINQ. My data type in database is nvarchar but when I use linq like MyDataContext dx = new MyDataContext (); KeyWord keywrd = new KeyWord(); keywrd.name = txtName.Text; dx.KeyWords.Add(keywrd); . . . dx. SubmitChanges(); name is in arabic and when I check the databse it inserted ??? insted of none unicode value. Please help. Thanks, Ahmad... Read More...
|
-
or doesn't call SubmitChange() at all in the business logic method and do it like, order.DoSomeBusiness(); order.DoAnotherBusiness(); db.SubmitChange(); (I have a mechanism that pass DataContext around the method calls) I think calling SubmitChange() in every method would be inefficient when I call several business methods. But most of the time I simply call one business method so making another call to db.SubmitChange() is also inconvenient. Which is the best practice? Read More...
|
-
I have been working on an issue tracking application and have decided to do my database access using linq. The only real problem I have run into is how to link two tables that have multiple foreign key relations when using the LinqDataSource control. I have table [Issue] and table [User]. [Issue] has fields issue_creator_id and issue_assigned_id, both related to [User]. The problem that I run into is that when I access Issue.User.user_name with linq, I cannot choose between the creator or assigned Read More...
|
-
In the LINQ to SQL .NET Language-Integrated Query for Relational Data white paper 3.2, Because of this the DataContext manages object identity. Whenever an a new row is retrieved from the database it is logged in an identity table by its primary key and a new object is created. Whenever that same row is retrieved again the original object instance is handed back to the application. In this way the DataContext translates the database’s concept of identity (keys) into the language’s concept (instances). Read More...
|
-
If I define a collection of Member objects like this: Code Snippet public class MemberCollection : List Member > { } ... and try to populate this collection using LINQ to SQL like this: Code Snippet public MemberCollection GetMembers() { using ( VenomDbDataContext db = new VenomDbDataContext ()) { return ( MemberCollection )( from m in db.Members orderby m.LastName, m.FirstName ascending select m).ToList Member >(); } } I get a wonderful exception like this: System.InvalidCastException: Unable to Read More...
|
-
Hi. There's lot of information on generating the class model from existing database. But - for a new project - how can I generate a new database schema FROM a newly designed class model? I'm guessing LINQ does not support forward translation, right? Thanks, Atish Read More...
|
-
Hi, How Can I use IN opeator in dlinq query? what is the syntax for that? For Example select * from patients where PatientId in (1,2,3) what will be the similar syntax for this dlinq query? Thanks In Advance, Regards, Sachin Shinde Read More...
|
-
When changing an XML column using SetElementValue, change is not noticed by Linq. I have a column in a table that is of type XML. The column name is Attriubtes. The table is components. I have code that wants to add or update elements in the XML, and I did it with a method like: public XElement Attributes { get { return component.Attributes; } } public void SetAttribute( string name, string value) { Attributes.SetElementValue(name, value); } This code worked fine, but the DataContext never thought Read More...
|
-
I have a simple model made in the designer. A single table made to two classes (Page, News) with inheritance on a PageType property that is an int. I can select object from the context with typeOf etc, and it works fine. But, when I´m trying to insert a new object that is not of the default type (Page), I get an error. Code Snippet Object reference not set to an instance of an object. System.NullReferenceException: Object reference not set to an instance of an object. at System.Data.Linq.ChangeTracker.StandardChangeTracker.StandardTrackedObject.SynchDependentData() Read More...
|
-
Hi, I am trying to write a certain LINQ query in C# but i'm unable to wrap my mind around this one. I have two tables (of relevance to this issue) in my database. One contains cars and the other contains cars_drivers (relationships between cars and drivers). I don't know if it's really needed but here's how my tables are set up: "Car": Id (uniqueidentifier), Name (nvarchar(50)) "Car_Driver": Id (uniqueidentifier), CarId (uniqueidentifier,fk to Car.Id), DriverId (uniqueidentifier) A car may have multiple Read More...
|
-
In this post, I'm going to give out one of my favorite secrets - how to read specifications quickly, with a high degree of retention. I have a particular technique, and if you use this technique, you may read specs more quickly, and you will remember more after you have read them. Please excuse the length of this posting - however, I'm going to bet that if you will take the 10 minutes or so that it will take to read it, you might save this time many times over the next time you sit down to read a Read More...
|
-
I've been reading about the predicate builder at http://www.albahari.com/nutshell/predicatebuilder.html using a method like this: public static Expression Func bool >> Or( this Expression Func bool >> expr1, Expression Func bool >> expr2) { var invokedExpr = Expression .Invoke(expr2, expr1.Parameters.Cast Expression >()); return Expression .Lambda Func bool >>( Expression .Or(expr1.Body, invokedExpr), expr1.Parameters); } To compose OR expressions: var builder = PredicateBuilder .False >(); builder Read More...
|
-
I have spent a couple of days trying to figure this one out. List Book > books = new List Book >(); // add a book with ID 123 Book bk = new Book (123); // add a chapter with ID 15 and Price $10.00 bk.Chapters.Add( new Chapter (15, 10)); var result = from book in books where book.Chapters.Exists( delegate ( Chapter chapter) { return chapter.ID == 15; }) && book.Price > 10 select book; This works great. Returns one object. I know, the first question is "Why are you doing this?". Let's get to the next Read More...
|
-
I'm learning LINQ by just diving in. I've written a small app that uses LINQ for CRUD activities in a simple database. I was wondering if it is acceptable to return an IQueryable interface to display data on a form. Here is how I'm doing it: First, in data access class I implement this: public IQueryable GetAllSubcategories() { var subCat = from sc in this .dataContext.Subcategories from c in this .dataContext.Categories where sc.CategoryId == c.CategoryId select new { sc.SubcategoryId, c.CategoryName, Read More...
|
-
I have this table set up table A { Description, TableBId } table B { Id, Name } I have a data source I cannot use a "Select" property. a grid view is binding to the data source. And I need to be able to say this with the columns -- the description field from table A -- the Name field from table B Any ideas on how I can achieve this? Thanks, Nick Read More...
|
-
How does link detect and track changes on objects? If doing IL does it intercept on a private field if specified, or on the public set? Read More...
|
-
hi i have this code Code Snippet From Casos_x_turnosd in Casos_x_turnos select new {Casos_x_turnosd, s=(Casos_x_turnosd.Total_Pacientes> 44 ? "s" : "n" )} in C# how express it in VB Read More...
|
-
I've been trying the code at http://tomasp.net/blog/linq-expand.aspx to allow expressions to be held as variables, ie: Expression Func , int ?>> test = (b => b.entryid + 10); var query = con.People .ToExpandable() .Where(b => test.Compile().Invoke(b) > 30); But the samples make use of a .ToExpandable() extension method, which won't compile on RTM. For example, I get an error that ExpressionVisitor is inaccessable. Is there another way to contruct this like of logic? Thanks, John Read More...
|
-
Hi, i've written the following class: public class A { public static implicit operator A(B instance) { return new A(instance); } // ... } However, when i create a List and call Cast ().ToList() i get a runtime error saying "Unable to cast object of type 'B' to type 'A'". However, when i do a simple implicit, or explicit, cast from B to A it works fine. Thoughts ? Read More...
|
-
I've been messing with the LINQ to SQL designer in Visual Studio 2008, and I noticed that there is a "Unique" property on an Association that can be true or false. I've tried setting this in the designer but I haven't seen any changes in the XML (or, consequently, the generated code). Am I doing something wrong? If it's a bug, is there any way to generate IsUnique property on an Association's attribute from the XML level? Thanks. Read More...
|
-
Hello everyone, I have a problem with the generation of the .dbml file. What I'm doing : I have a web project created in vs 2008 beta 2, I add a Linq to Sql file and drag and drop the tables I need from the Server Explorer. After saving, the content of the .designer.cs file is : public partial class MyDataContext : System.Data.Linq. DataContext { private static System.Data.Linq.Mapping. MappingSource mappingSource = new AttributeMappingSource (); #region Extensibility Method Definitions partial void Read More...
|
-
|
|