|
|
June 2008 - Posts
-
The Where extension method commonly used in LINQ queries is very handy, but was a tad lacking in a certain circumstance I encountered not too long ago. Check out http://www.patrickdewane.com/2008/06/ienumberable-wh.html for a different implementation of Where that I named WhereFew that can come in handy when filtering sorted data. Read More...
|
-
Hi, I've got the following issue. It seems that the overload of Expession.Call for static methods cause a wrong exception. Maybe the parameter check has got a wrong implementation. Could you clarify that, please. Benjamin static void Main() { ParameterExpression param = Expression .Parameter( typeof ( String ), "text" ); //var mi = typeof(Console).GetMethod("WriteLine", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(String) }, null); //MethodCallExpression method = Expression.Call(mi, Read More...
|
-
Hi all, I wrote the following code to insert data into the table. Although it is successfully building, its adding the data into the table. Which means after the execution of the program, the table doesnt have the inserted data. private void btnSubmit_Click( object sender, RoutedEventArgs e) { if (txtRName.Text != "" && txtUserName.Text != "" && pwbPassword.Password != "" && pwbConfirmPass.Password != "" && ComCountry.Text != "" && ComSecurity.Text != "" && txtAnswer.Text != "" ) { UsersDBDataContext Read More...
|
-
Hi, I found how to add validation to a Linq-to-SQL class, but it's not the same for Linq-to-Entities. I'm trying to find out how to add validation for updates to a complete entity as mentioned here...such as checking multiple properties in a single update method before changes are sent to the database. http://msdn.microsoft.com/en-us/library/bb629301.aspx Read More...
|
-
Hi, I have a string like "msdn$//$forum" and i want to split it into two strings are "msdn" and "forum". please help me in this regards, Shiva Read More...
|
-
Hi! I'm using Linq to query objects of a custom class within a collection. I display the results in a Silverlight 2 Beta 2 DataGrid. Basically the object holds two numeric values (receipt, expense) and others that are not affected. Imagine there's a certain amount of money to start from (that amount is being stored somewhere else) and we add receipts and expenses to increase or decrease that amount. I need to display the accumulated amount after each receipt/expense as in the following example: receipt Read More...
|
-
An unusual subject for this blog that has been mostly about components I have worked on. But the event yesterday was memorable and worth sharing. The event has been covered widely so I won't even try to broadly summarize. Insted I will list what I found interesting. I was lucky enough (one of 2k lottery winners out of maybe 20+k who were interested) to get a seat for in-person viewing. There is no substitute to hearing from the man himself and his business partner of 28 years (and a friend/associate Read More...
|
-
Hi, I am new to Linq to Sql and have a minor problem. I created an object name 'Family'. The 'Family' object then has an object of type EntitySet which stores objects of type 'Member'. So far I have no problem to order the returned Families depending on the dateTime they where formed. However I cannot manage to sort its members depending on the day they where born! Is there a way in Linq how I can sort the child objects when retrieving the parent object? Regards, Sim085 Read More...
|
-
I would like to execute a query with multiple joins and return an object with a hierarchy of sub-objects. Here is the query in SQL: select * from apt_code_lu lu join apt_main m on lu . apt_id = m . apt_id join apt_rwy_end re on m . apt_id = re . apt_id join apt_track t on re . rwy_end_id = t . rwy_end_id join apt_subtrack st on t . track_id = st . track_id join apt_seg seg on st . subtrack_id = seg . subtrack_id where lu . apt_code = 'ATL' and lu . cntry_code = 'US' Basically an airport contains Read More...
|
-
I have four classes: ddLists - List(of ddList) ddList ddListItems - List(of ddListItem) ddListItem Each ddList has a list of items, so it has a ddListItems property. What I want is a set of list items that meet a particular criteria … but I can't seem to figure out how to do it with LINQ. At first I tried this: From li as ddListItem in ????? There is no massive container of all of the list items. So I could not go in that direction. Nor could I do any join that I could see because they all seem to Read More...
|
-
Hi! I use the Linq-to-Sql designer so to model 3 tables and 6 stored procedures and i use one of these to fetch some Customer data (the usual stuff like CustomerName, Address, Country etc). I use it like this: TestDataContext test = new TestDataContext(); var mclients = test.MasterClients_fetch(0); and then i assign the mclients to the DataSource property of a DataGrid and it works well, my Customer data are displayed on the DataGrid. But when i try to do a further select in mclients, then the DataGrid Read More...
|
-
Hello, I am using LinqToSql together with SQLServer Compact Edition 3.5 When committing changes I am getting the exception: "The transaction can not be committed if there are any opened cursors in the scope of this transaction. Make sure all data readers / result sets are explicitly closed before committing the change." Code Snippet using (Db db = new Db("file")){ try { // ------------------------------------------------- Ctx.Connection.Open(); Ctx.Transaction = Ctx.Connection.BeginTransaction(); Read More...
|
-
I'm using the version of SQL Server that comes w/ VS2008, adding a database (.mdf) file to my App_Data folder. That database w/ a single table - 'Customers'. There are only about 3 columns in said table: ID - uniqueidentifier FirstName - nvarchar(50) LastName - nvarchar(50) I used the LINQtoSQL designer to generate my DataContext class. I then removed the Customers table from the db. I then called CreateDatabase from my DataContext class and every time, it errs with the following info: Illegal characters Read More...
|
-
Hi everyone! I have the following problem: I have a class that gets two type parameters (TypeOne and TypeTwo). The class is inherited from "List (Of TypeOne)". I overloaded some methods (like Add, Remove etc.); these methods contain a conversion from TypeTwo to TypeOne. This means that the first type of my class describe how the list elements are internally stored while the second parameter defined how i want to access them. This makes it possible for me to say "List.Add(item As TypeTwo)" and internally Read More...
|
-
Hi, i saw an example of Linq-to-sql where the designer has generated some partial methods' declaration so we can provide the implementation later and do some processing on a let's say, property grid. examples are: partial void OnLoaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnCustomerIDChanging(string value); partial void OnCustomerIDChanged(); partial void OnCompanyNameChanging(string value); partial void OnCompanyNameChanged(); partial Read More...
|
-
Ok, I have a bit of a curly one here that I'm looking for a solution for. The problem is the need to offer multiple/customisable user views, which equate to subsets of an IQueryable set, including some related data. I have tried 2 approaches to tackle this so far: 1) Emit a new Dynamic Type representing the subset that would ordinarily be an anonymous type when hard-coded. 2) Generate multiple combinations of the fields into a massive switch statement based on the user view filter. The 'filter' is Read More...
|
-
Hi, I'm new to Linq, but I am a highly skilled with Oracle SQL, I have two List<> collections with a relationship between the two: listA = List listB = List The primary/foreign key will be "valueAB" There could potentially be none to many child records contained in B that map to one single record in A, I want to combine the two in a linq query that will create a new collection that contains a collection of all records in B (this would be List that is a member in List, see below..... for example, Read More...
|
-
Which one is better & why ? 1. Create DataContext instance while constructing class. 2. Create it using "using" statement for each function e.g. using ( MyDataContext db = new MyDataContext ()) { //use db } Thanks in Advance Read More...
|
-
Table1 has a primary key id (auto-increment) and Table2 has a foreign key id linked to that of Table1. If I do an insert into Table1, how do I retrieve the value of id to do a matching insert into Table2? Thanks Read More...
|
-
A LINQ to SQL .dbml contains 4 tables (framework 3.5 some classes originally 2.0). Some of the tables have identical columns like ID, quote, etc... The identical columns are causing an error: 'Public Property ID as Integer' has multiple definitions with identical signitures. The public properties reside in unique classes so the polymophism should be ok. Why does the 'multiple definitions' error occur? Read More...
|
-
Given a List of the following, how do I get the MsgText from the most recently received message for each HostIp? Do I need some sort of nested query for this, or am I missing something easy. Thanks in advance for any help. class Message { public string Hostip; public DateTime MsgTime; public string MsgText; } //This seems close, just a little off var selection = from p in VwMessages group p by p.Hostip into l select new { Ip = l.Key, MaxTime = l.Max(p => p.MsgTime) //want the text, not the time }; Read More...
|
-
Hello... After spending quite a few hours trying to solve this, I need some help I've created a left join Code Snippet var result = from inst in baseData join sub in this ._subscriptionInfo on new { inst.Origin, inst.Destination } equals new { sub.Origin, sub.Destination } into instsub from sub in instsub.DefaultIfEmpty() The _subscriptionInfo has a column called ProfileID, if we look at it as a normal table join, the SQL output will be: Code Snippet inst.Ori inst.Des sub.Ori sub.Des sub.ProfileID Read More...
|
-
Hi, I'm new to Linq so this might be a stupid question. I have the class Orders which I've decorated with the Table and Column attributes and : Code Snippet [ Table (Name = "OpenOrders" )] public class Order { [ Column (IsPrimaryKey= true )] public string ClOrderID { get ; set ; } } public class OrderDatabase : DataContext { public Table Order > Orders; public OrderDatabase( string connection) : base (connection) { } } My program has three instances of a list of Order, called Open, Filled and Rejected. Read More...
|
-
The Linq to SQL designer is broken in my installation of VS 2008, whenever i try to open a dbml file i get a message box saying "The operation could not be completed" (Very usefull error!) Ive been working on a VS addin which uses linq, everything was working fine yesterday but when i tried to open the project today it wouldnt compile because of the following error Error 1 Build failed due to validation errors in [...]IssueTrackerDataContext.dbml. Open the file and resolve the issues in the Error Read More...
|
-
hi, there, I'm using LINQ with POCO in my current project, I have the code like this for insert operation: using (ClaimDataContext dc = new ClaimDataContext()) { dc.Log = new Utils.DebuggerWriter(); dc.GetTable().InsertOnSubmit(request); dc.SubmitChanges(); } My question is how to get IDENTITY value back for current entity once it has been inserted. I don't want to use another LINQ expression to query the top 1 record from database, because I noticed that the generated sql contains the identity value Read More...
|
-
I have following relationship Customer | |__[1:N]CustomerAddress and... Country | |__[1:N]CustomerAddress --in other way.. Customer | |__[1:N]CustomerAddress ---> [1:1] Country ---------------------- When I try to execute following qry, Country is always coming as "null" Customer MyCustomer = null ; DataLoadOptions lo = new DataLoadOptions (); lo.LoadWith Customer >(c1 => c1.CustomerAddresses); lo.LoadWith CustomerAddress >(ca => ca.Country); db.LoadOptions = lo; MyCustomer = ( from c in db.Customers Read More...
|
-
A little break from my "LINQ to SQL tips" series of posts. A recent vote of no confidence on a related component orchestrated by community activists reminded me of many questions I have fielded and how the design team approached the design of LINQ to SQL (and also core LINQ APIs and C# language changes for LINQ). Nah, that’s for another day when it is cloudy and raining. Instead, let’s talk about my recent dream. Or rather, a nightmare! But first turn off your flame throwers, grab a cup of coffee Read More...
|
-
When using the runtime to generate the SQL updates, can you turn off concurrency checking for your entire entity diagram so the SubmitChanges() uses only the Primary key columns for sql updates? It seems cumbersome to have to go through column by column of each table to set the update check to "Never" in the Visual Studio diagram. ... my code to test an update... Topic newTopic = new Topic(); newTopic.TopicId = 60; ctx.Topics.Attach(newTopic); newTopic.TopicName = "Change tracking test updated " Read More...
|
-
I have a Custom Object MyNumber, which takes 2 numbers and when Calculate method is called sums them up and saves them in a public property. however when i create a bunch of MyNumbers using LINQ and call the calculate property the sum is not stored. Why? Code Snippet Public Class MyNumber Private mNumber1 As Integer Private mNumber2 As Integer Private mSum As Integer Public Property Number1() As Integer Get Return mNumber1 End Get Set(ByVal value As Integer) mNumber1 = value End Set End Property Read More...
|
-
Is there any approaches to get the group's count during the LINQ query expression. Code Snippet var result = from record in datamodel group record by record.Name into newGroup orderby newGroup.Key select new { TheGroup=newGroup, AllGroupCount=??? }; If I want to know how many groups are there during the expression without select it, how can I do that. newGroup.Count() just told me how many records are there in the group, I cannot get the group's count information during the expression. Read More...
|
-
Hi all, I find it odd that I cannot access the object returned in the method below - although all compiles well. Can you see why this may be a problem ? I know from previous tests that adminResponseObj below has the 3 properties assigned in the anonymous method. TIA public object GetCompanyProfileAdminFeedback( Guid userId) { object toReturn = null ; // Get the member object from which we can get the company id foreign key DBLinq. Tb_member m = gdb.Tb_member.Single(mbr => mbr.User_id == userId); Read More...
|
-
I'm attempting to generate code by building a lambda expression and compiling it using the methods defined in the System.Linq.Expressions namespace. I've run into some very odd behavior and I was wondering if someone could shed some light on the problem. I'm attempting to create an expression like this one programmatically using the Expression API: Action compiled = x0 => new Action(x1 => Do(() => this.DoSomething(x1)))(x0); Assume I've defined a parameterless Action delegate, a Do method, and a Read More...
|
-
Hi group, I would like to get advice on how to specify rules for symbolic differentiation. Note that I am not concerned with any rules-processing engine that would actually perform the differentiation - I just want to use Linq to define the relationships. Below I show two approaches, but neither looks clean. The problem with the first approach ("Attempt1" below) is that my rule uses equal sign to define the relation. As a result, a rules engine would have to have knowledge of rules being encoded Read More...
|
-
Hi, I have a basic question on Linq query i have for example 2 tables: Categories ID Name Products ID Name CategoryID I would like to create a method that will return my one product with the category name. I've tried this, but didn't success. Here is my code: public static Product GetProductByID(int ID) { using (MyDataContext db = new MyDataContext()) { var Results = from p in db.Products where p.ID == ID select new { ID = p.ID, Name = p.Name, CategoryID = p.CategoryID, CategoryName = p.Category.Name Read More...
|
-
In a wcf services , one method to do update ,and call the datacontext.submitchanges method with no problem . And ,then query the data from that datacontext, the data is not the value just updated . Why did this occured ? Read More...
|
-
Hi, testing the Attach method, I'm trying to update an existing record in my database that has a Topicid of 60. I'm not sure what I'm doing wrong to have the SubmitChanges work. There is no error but I'm also not seeing any changes to my record. DataClassesDataContext ctx = new DataClassesDataContext(); Topic newTopic = new Topic { TopicId = 60, TopicName = "Change tracking test updated " + System.DateTime.Now.ToString(), TopicTypeId = 1 }; ctx.Topics.Attach(newTopic); ctx.SubmitChanges(); Read More...
|
-
Would it be possible to select all the distinct strings from a collection in the following form? IDictionary> groups; Thanks Read More...
|
-
In our family, we have a rule – on Mother's day, my wife basically gets to set the agenda for the entire weekend. And, as appropriate, she doesn't have to lift a finger around the house. And on Father's day, the same rule applies for me. But on all other weekends, normal rules apply. This year, because my wife was out of town on the actual Father's day, we shifted Father's day to this last weekend, and my choice for how to spend the weekend was to write the code that I'm presenting here, and to write Read More...
|
-
Hi all, I'm kinda new to all this .net shabang so any help would really be appreciated. I have 2 objects; Client and payments Client object consists of a number (IList) of Payments and Payment Object has one Client. Now my question is this: I am currently loading a payments list using linq like this: IEnumerable e = from PaymentDTO p in Container select p; Now if i try to access this: foreach (PaymentDTO payment in e) { MessageBox.Show (payment.Client.Name); } The above gives me a null Client? Why Read More...
|
-
Hello Guys, I have the following scenario. Two Tables Customers and Orders . Each Customer will have multiple Order and I have a parent children relationship between the tables. I created all the standard stored procedures for each table. I need to do the Following. For a certain customer, I need to load from DB the Customer Info and all related orders and then I need the data to be stored so I can work in disconnected mode and then I can save later my changes. I need this to happen all in stored Read More...
|
-
Hi, I'm a little confused on when exactly to create the Datacontext and when it tracks changes on objects. In the Asp.NET Pro, June '08 issue, there is an article that states "to be able to keep track of the Customer object's changes throughout the life of the object, the DataContext must be created *before* creating a new instance of the Customer class. See article at http://www.aspnetpro.com/PDF/Issues/aspJUNE2008.pdf In "Pro LINQ" by Joseph Rattz, on page 508, it's similar in that the context Read More...
|
-
So I have a table "Employee" and wish to have a business class "Employee". This was possible before LINQ. But now that I am generating a .dbml for the LINQ DataContext, it "takes over" those names for its classes. I'd hate to have to name my business classes "EmployeeClass" or some other non-ideal convention. Any thoughts? Thanks, Ron Read More...
|
-
Hi, I've just started using linq and was wondering if anyone could point me in the right direction for a few things. ok so I have a product catalogue and I want a linq query to filter products based on a few criteria. firstly my product categories are in a heirarchy so I want to select all the products from my current category plus all the products from all the categories which are decendants of the current category. [Currently doing this using CTE's in a stored procedure (selectchildcategoriesbycategoryid)] Read More...
|
-
I have this query in SQL I want to conver to Linq. Compeltely lost since I am new to LINQ: Here is the Query: SELECT (SELECT COUNT(*) FROM Projects C2 WHERE C2.Project_ID >= C.Project_ID And Project_Enabled='True') AS SrNo, Project_ID, Project_Title FROM Projects C Where Project_ID=8 AND Project_Enabled = 'True' Here is my current LINQ without the sub-query: from p in db.Projects where p.Project_id == project_id && p.Project_enabled == true select p; Please help me. Read More...
|
-
Hi all, I have the following expression var crResponded = from c in gdb.Tb_company_review where c.Id_company == m.Id_company orderby c.Updated_on descending select new {c.Company_name,c.Admin_comment,c.Description}; if (crResponded.Any()) { var latestRecord = crResponded.Take(1); } How do get to the field I declared c.Company_name, c.Admin_comment that I obtained ? If I do a foreach loop with only one field defined (not 3), I can get to one of the fields. However, how do I get to all 3 I am looking Read More...
|
-
Hi , I have a table without primary key. I need to do insert,update,delete operations for that table using linq query.But linq is not supporting for the tables who are not having primary key. Shiva. Read More...
|
-
Hi, I have a sql query ,i need to transfer into Linq query is SELECT DOMAIN_ID FROM TB_DOMAIN WHERE DOMAIN_ID NOT IN ( SELECT D . DOMAIN_ID FROM TB_DOMAIN D , TB_CHARGE EC WHERE D . DOMAIN_ACTIVE = 0 OR ( EC . DOMAIN_ID = D . DOMAIN_ID AND EC . CHARGE_ID = '12345' ) ) Please help me..in this regards, Shiva Read More...
|
-
Hi all, I have developed a simple login module. I used LINQ technology to write the query. First I did the mapping part with the database. It was successful. Then I used an instance of my mapped class(subclass of DataContext class) to query the database. I created a SQL server database having a simple table. I was able to read the data from the table and validate the user name and password. But I dont know how to handle the situation if I tried to login using a non existing user name. Because If Read More...
|
-
Hello everyone: I have a basic question about LINQ. Let’s say that I’m working with a singleton WCF service that several users access at the same time. In that service various objects CUSTOMER may exists at any given time, because different users are working with different objects. Let’s say that it requires 3 calls to 3 different methods of the service for a user to “complete” work on a given CUSTOMER object, so it’s life is spanned between calls. What about if user A is on the second request, that Read More...
|
-
My question is really one of building an n-tiered application architecture using Linq. Currently I use business objects to call the data access layer which in turn does the appropriate Linq query and returns the Linq object (or DTO or EO..whatever you want to call it). I then work with the Linq objects directly, performing business logic and databinding. In essence I am using Linq objects as business objects in themselves, partialing them out to add business logic. I'm not certain as to whether this Read More...
|
-
I used the Add > Function Import feature in my model's .edmx diagram by selecting a stored procedure. It then appears in the Model browser tab as EntityContainer:myEntities > Function Imports > MyFunction How do I reference that function or method in my code? The propeties say it should be part of the myEntities.MyFunction but it doesn't appear in Intellisense anywhere when I create the entities instance?? Read More...
|
-
Hi, I have a simple diagram that I'm trying to map stored procedures to. A TopicType table and Topic table that references the TopicType.TopicTypeId as a FK. Error 2048: The EntitySet 'Topic' includes function mappings for AssociationSet 'FK_Topic_TopicType', but none exists in element 'DeleteFunction' for type 'databaseModel.Topic'. AssociationSets must consistently mapped for all operations. I've mapped insert, update, & delete procedures to the Topic table but I still get this error. I'm not sure Read More...
|
-
Sorry for the bump on this. I posted yesterday and just looking for anything. I am new to LINQ so I have what is probably a basic question. I have filled 2 datasets: Dim DB2SQLData As New db2SQLDataSet() Dim sheet2Adapter As New db2SQLDataSetTableAdapters.Sheet2TableAdapter Dim noteAdapter As New db2SQLDataSetTableAdapters.NotesTableAdapter sheet2Adapter.Fill(DB2SQLData.Sheet2) noteAdapter.Fill(DB2SQLData.Notes) The sheet2 table has a one to many relation to the notes table. I have dragged over the Read More...
|
-
Hi, Im trying to insert a new element which joins to another element (many-to-one) by setting the FK ID to the id of the joined element however i get an "An attempt was made to remove a relationship between a ResourceList and a Resource. However, one of the relationship's foreign keys (Resource.ResourceListID) cannot be set to null." error. I can set the join member to an actual object instance, however when I Serailize it to the WCF data service the one-to-many join item is lost as the serialization Read More...
|
-
I am a newbie to PowerShell scripting. This is probably pretty obvious to anyone who has taken a look at the PowerShell scripts that I've written. Fortunately, there are people around who can improve on my efforts. Developer/Author Doug Finke has developed a much, much cleaner version of the PowerTools BulkMailing.ps1 script that generates multiple wordprocessing documents from a source XML file. The best improvement is how the text of the document is specified in the script. The document is specified Read More...
|
-
Hi, I am new to LINQ. As far as i know, to work with Sql Server, we can use the following procedure. 1.Create a dbml (say DataContext) file. 2. Open server explorer, select the database. 3.Drag the required (sp/tables..) to the dbml. 4. Now we can access the db objects by creating an instance of the DataContext. This is fine. My doubt is regarding sqlmetal tool. (which is said to be a better alternative of the above procedure?) Can u pls help me regarding the following. What are the steps involved Read More...
|
-
Hi, I'm finding myself more and more just trying to check if a relationship exists i.e. in this example whether a staff member is a manager. I'm putting everything in try and catch blocks but I always thought that try and catch blocks were for unusual activity only. How can I test to see if a staff member is a manager without using try and catch blocks? What's the most effective way to do a test to see if a record exists with a binding? Thanks, Code Snippet var staff = db.Staffs.Single(st => st.Managers Read More...
|
-
public ADAPDocument GetADAPDocByID( Guid docId) { // do We have a valid guid? if (docId == Guid .Empty) { InvalidArgumentFaultDetail .ThrowException( "DocumentId" , "DocID cannot be null." ); } // Query time.... //using LogicorShippingData.ADAPCalculatedPriority using ( LogicorSystemEntities db = new LogicorSystemEntities ()) { var adap = ( from ad in db.ADAPDocumentView where ad.guid = docId select ad); I get an error line under the word "where" Error 1 Cannot convert lambda expression to type 'string' Read More...
| |
|