|
|
February 2008 - Posts
-
Can someone give me an example of how to pass the xml file as the mapping source in creating the datacontext? Thanks Code Snippet Northwind db = new Northwind ( @"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI" ); public Northwind( string connection, System.Data.Linq.Mapping. MappingSource mappingSource) : base (connection, mappingSource) { OnCreated(); } Read More...
|
-
What does Code Snippet /serialization:Unidirectional with the sqlmetal command? Read More...
|
-
Hello, I'm new to LINQ and ran into a litte problem: I've got three tables: Table Vendor: VendorID (primary key) VendorName Table Product: ProductID (primary key) ProductName VendorID (foreign key) [some other columns here...] Table Version: VersionID (primary key) VersionName ProductID (foreign key) [some other columns here...] Now i want to get all vendors whose name contains a specific string (filter) or whose products names contain the filter or it's versions name contain the filter (I hope you Read More...
|
-
I was wondering if it's possible to get the database that an object generated by dlinq was grabbed from So, if for example I do Code Snippet var person = from p in datebase.Person where p.PersonCode == SomePersonCode If I then have a method within the person object created that does something with the database, can I get hold of the database that person object was created from? Thanks! Read More...
|
-
Is there any way from the LINQ to SQL designer in Visual Studio to specify that a stored procedure parameter should be an enum rather than a string? The underlying database stores nvarchars representing enums from my C# application. I can modify the appropriate row for my table in the designer to specify the enum type. However, I don't see any way to do this for stored procedures. Read More...
|
-
Hi, I am doing a Linq to SQL join var something = (from TB1in db.Table1 join TB2 in db.Table2 on new { TB1.criteria1, TB1.criteria2, TB1.criteri3 } equals new { TB2.criteria1, TB2.criteria2, TB2.criteri3 } select TB1); The syntax looks fine to me, but it alwasy give me an error : The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'. If I remove any 2 fields in the join, then it is going to work.. Can anyone help ? Read More...
|
-
What is the recommended pattern to update (or insert/delete) a child? The framework should check (an update) a timestamp column in the parent only (at least within the composition pattern). Thanks Read More...
|
-
I need all associated payments to a regional in a year and month. I have the query: var list= from p in DB.Payments join a in DB.associateds on p.Associated equals a.ID_Associated join r in DB.Regionais on a.ID_Regional equals r.ID_Regional where p.PaymentDay>= new DateTime(year, month, 01) && p.PaymentDay select new { p.Value,r.ID_Regional, r.Name, r.State }; It returns to me, for example: [0] {Value = 100, ID_Regional = 32, Name = RegionalSP, State=SP }; [1] {Value = 150, ID_Regional = 32, Name Read More...
|
-
Hi, I'm having a problem with creating a SQL to LINQ entity with an integer version column for optomistic concurrency. I don't want to use timestamps as this can be volatile with host system time changes. This also causes a problem with PDA's that have been dropped in the field and reset to factory default time settings so int is the safest. I've configured the DataContext field to be identical of that specified in the MSDN documentation. http://msdn2.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.isversion.aspx Read More...
|
-
The following scenario is causing me indigestion. Does datacontext load entire tables or is my watch expression causing me to force loading all the table contents. I create a datacontext with a table (entity) structure like this. applications contents versions The application rows have an ID and a Name. The content rows are related to application rows by ID. Similarly the version rows are related to the content rows by a content Id and version number. The query var app = from apps in applications Read More...
|
-
I've read several places that Microsoft recommends against having one Big Giant Context where you have your entire object graph laid out. So the obvious solution is to break it all up into smaller "units of work"-style contexts. Makes sense. However, here's my question regarding this (using Northwind as an example): My "Supplier" context is going to need a Product entity. My "Orders" context is also going to (ultimately) need a Product entity. Not to mention if I decide to have a "Products" context Read More...
|
-
What I want to do is return a list of all the cities in a database along with the number of houses in each city. Currently, I am first retrieving a list of the cities and then interating through each one and quering the database for the count. This is slow and I know I could do it faster with T-SQL and a stored procedure if I wanted to. Instead, I would like to know if it is possible to do this in Linq to SQL. The database has three tables that I am interested in. The first is re_houses which contains Read More...
|
-
Okay, I'm trying to wrap my head around querying XML with LINQ, and I just can't grasp. Here is some sample XML that I want to query: Code Snippet What I'm trying to write is an external tool that will publish our websites using NAnt right in Visual Studio. Based on the open solution, my app grabs the project name and where it is to be published to (development/production, passed in as default arguments). I've been able to get the current project name and where to publish to, and what I'd like to Read More...
|
-
I am trying to use linq to delete rows from SQL Server database. var something = (from inv in InventoryLTD where inv.rate == 1000 select inv) I tried the following foreach (var detail in something) { db.INVENTORYLTD.DeleteOnSubmit(detail); } db.SubmitChanges(); and db.INVENTORYLTD.DeleteAllOnSubmit(something); db.SubmitChanges(); both of them only help me to delete one row from the table, but var something should have at least 100 rows . Can someone tell me why ? Thanks Read More...
|
-
I am wondering if it is possible to somehow create a user edfined class and then provider a SQL Type mapping for that class so that I can use it in Linq.E.g. Assume I have a class called IntWrapper and I want to pass that in to my query. Code Snippet IntWrapper x = new IntWrapper (5); var query = from s in _mainContext.SomeTable where s.Id select new SomeObject(s.Id) At the moment I get an exception telling me there is no supported translation to SQL. What I'd like to be able to do is tell the SqlProvider Read More...
|
-
Hi i'm using LINQ to fill a DataGridView: Code Snippet var result = from o in oMyDataContext.orders select new { o.NoOrder, o.Notes, mycol="test" }; BindingSource bs = new BindingSource(); bs.DataSource = result; dataGridView.DataSource = bs; //and i bind textbox1 to Notes field: (user can modify this field) textBox1.DataBindings.Add("Text", bs, "Notes"); when textbox are modified.. the event OnNotesChanged() (from MyDataContext) aren't triggered.. i suppose it's because of "select new {...}" (when Read More...
|
-
I am starting a new job in two weeks where I will be required to use Linq to retrieve data, so I thought that some preparation is due so that I can hit the road running. I have no problem with setting up DataContext's and querying data, but Updating and Inserting dont seem to do anything. The following is a function that I use to insert new data ... private void btnAdd_Click(object sender, EventArgs e) { Name name = new Name(); name.NameText = tbxNameToAdd.Text; dcNames.Names.InsertOnSubmit(name); Read More...
|
-
If you're inserting 100 records into a database using dlinq using InsertOnSubmit it appears to me that it fire's off 100 seperate insert statements, each one being a round trip to the server and back. Surely this would be much more efficient if it just fired off one statement with 100 inserts? Particually on a slower system. Is there a way to manipulate it into behaving like this? Read More...
|
-
I have been using Linq to SQL very successfully. However, today I have run into what I believe to be a severe bug. Example code: var highScore = (from s in context.SubjectScores where s.SubjectID == StateManager.CurrentSubjectID && s.UserID == Common.CurrentUserKey orderby s.Score descending select s.Score).FirstOrDefault(); This should make highScore = 0 if no records are found. Instead it throws an InvalidOperationException: Sequence contains no elements. Ok, thats not good... but there is no way Read More...
|
-
Hello, I've started programming just a few weeks ago, so excuse my ignorance. I'm developing a small interface to connect to a database. I started with express 2005 last month and now visual studio 2008. But I am confused about "how" to proceed , which direction to take. I've seen a lot of movies on the msdn site and I can see that similar things can be done with the datasets and with linq as well. I found great utility in linq now updating all my objects collections to the database without much Read More...
|
-
Below is a code snippet from the the DataClasses1.designer.vb file generated by VS 2008. This is the extension method signature provided by VS2008. Code Snippet Partial Private Sub Oncr_trans_accountChanging(value As Integer ) End Sub I need to modify the template (if one exists) to generate this line of code. I simply added ByRef to the signature. Code Snippet Partial Private Sub Oncr_trans_accountChanging(ByRef value As Integer ) End Sub The reason for this is, when the below generated code executes Read More...
|
-
i've been trying to convert Matt Berseth's article on Building an Address Book in ASP.net 3.5 and i've hit a wall. The following code give me a type expected error at the first select new. anyone know what silly mistake i'm making. thanks in advance Code Snippet Dim xml = XDocument.Load(Server.MapPath( "app_data\employees.xml" )) Dim alphabet As Char() = { "A" , "B" , "C" , "D" , "E" , "F" , "G" , "H" , _ "I" , "J" , "K" , "L" , "M" , "N" , "O" , "P" , _ "Q" , "R" , "S" , "T" , "U" , "V" , "W" , Read More...
|
-
Hopefully this is a very simple question. In my ASP.net application after running a Linq statement do I need to explicitly close the database connection and set the Linq object to nothing? I've found I can do this: Dim DB as new MyDBNameDataContext Dim Linq_Results = From ............ ... ... Linq_Results = nothing DB.Connection.close() If I don't do the DB.connection.close() will it automatically be closed somehow? I'm just looking for the best way to optimize the connection pooling and being as Read More...
|
-
Hi, I'm wondering if somebody can help. In normal SQL I can do a query like: SELECT count(UniqueId) as RecordCount from TableName where Flag=1 How in Linq can I get a record count without bringing back all the data. I realise I can do Dim Linq_Results = From TableName in DB.TableNames WHERE Flag=True SELECT UniqueID Response.write(Linq_results.count()) However as I understand it I'm retrieving all the values for the UniqueId fom the database then counting the amount returned? Is there a build in Read More...
|
-
I'm using DLinq by hand, rather than using the standard designer, b/c I'm using the same class for serialization for WCF. I've got select statements to work (rather easily), but can't figure out updates, inserts or deletes. My class looks like: Code Snippet [ DataContract ] [ Table (Name = "Attendants" )] public class Attendant { [ DataMember ] [ Column (IsPrimaryKey= true )] public string ID { get ; set ; } [ DataMember ] [ Column ] public string Name { get ; set ; } } Examples online show an Add Read More...
|
-
Before I make a change to a table row, I first want to copy the contents over to an audit trail table that contains exactly the same fields except with the addition of the field ID_Arch which will contain the contents of the ID from the table proper. I could do this by: ArchOrders.ID_Arch = Orders.ID ArchOrders.Customer = Orders.Customer ArchOrders.Product = Orders.Product .... ... .. . ArchOrders.DateAmended = Orders.DateAmended If i make changes to the Orders table, I would have to make changes Read More...
|
-
This question is directed at MSFT: Are there any plans to add functionality for specifying sql optimizer hints in linq 2 sql generated queries? E.g. index hints, locking hints, join hints etc? Read More...
|
-
Hi, I have a problem to do the deleteonsubmit / deleteallonsubmit . I have a table without primary key, and I would like to use linq delete function to remove several records from the table. However, whenever it always show me a runtime error saying that linq can't delte without primary key. Is there anyway to customize the datacontext so that I can do the delete without a primary key? Thanks Read More...
|
-
Hola buenas mi pregunta es la siguiente como puedo hacer esta consulta en linq y vb.net select a,b,c from tabla group by a,b,c he conseguido esto pero solo tengo un campo Dim query = _ From product In products _ Group product By style = product.Field(Of String)("DESTINO") Into g = Group _ Select New With _ {.Style = style} saludos: Israel Read More...
|
-
I've got the following bit of code Code Snippet var Accounts = from userAccount in Db.UserAccount select new { userAccount.AccountCode, MaxBookingCode = userAccount.Billing.Max(p => p.BookingCode) }; The issue I have is that if there are no records in Billing then the Max will obviously return null. The problem is MaxBookingCode is assumed to be a non nullable integer. Therefore at the point of execution I get the error The null value cannot be assigned to a member with type System.Int32 which is Read More...
|
-
Hi, I am just beginning to work w/ LINQ. I have a data model set up and put a LinqDataSource and GridView on a page. It binds & displays ok, including paging and sorting. How do I enable editing? I followed a blog by ScottGu to edit using the GridView. Clicking on the smart tag of the GridView in Design view, there are no checkboxes to enable editing or deletion, as there would be for a SqlDataSource bound grid. I thought the LinqDataSource enabled two way binding, similarly to the SqlDataSource. Read More...
|
-
Hi, A simple Question, Why should I use dlinq / linq instead of ADO .NET? I can achieve all my requirements through ADO .Net What are the advantages offered through Linq? Regards, Sachin Read More...
|
-
Hi. I have tblCountry with primary key ID and tblProvince where countryID is a foreign key. What I want is the following, just in LINQ....... any takers?? SELECT * from tblCountry where ID IN (select DISTINCT(countryID) from tblProvince) This SQL basically will just give me the countries that has one or more provinces. Thank you Sarel Read More...
|
-
Hi I have a SQL like this: Code Snippet SELECT cp.pn_id, pn.pn_name, pt.pt_id, pt.pt_name, ps.ps_value FROM ContentProperties cp inner join PropertyNames pn on cp.pn_id = pn.pn_id inner join PropertyTypes pt on pt.pt_id = pn.pt_id inner join PropertySelections ps on ps.ps_id = cp.ps_id WHERE cp_type = 'ME' AND id = 886 Whats the linq code for this SQL ? Read More...
|
-
After uninstalling the LINQ preview, all my project files get a new . Why? I assume it is some left over configuration from the LINQ preview. The problem is I am using source safe in a production environment with lots of projects so I DONT want them to be manipulated like this! Any idea how to kill this leftover configuration problem?? Next time I will never install another extension preview on a developement box. I guess we are headed to the days of pre-development developement boxes. Joy. Thanks Read More...
|
-
Hello, I have a process that adds, updates, and deletes data. If an error occurs, I want to revert the changes. Can I use DataContext.Refresh method on a deleted item to restore it to its previous state, and it won't be deleted next time changes are submitted? Thanks. Read More...
|
-
I am trying to reproduce a SQL View into Linq. It is a fairly striaghtforward query that I am sure can be written differently. In any case, it was written this way after researching left outer joins etc for Linq to Sql. The code I produced in Linq is throwing and error that I can't seem to find any information on: <>f__AnonymousType1 not supported in aggregation operations Removing the last Subquery that retrieves the Max date entered allows the query to execute correctly. I like what I see thus Read More...
|
-
Hi, Experimenting with the "POCO Support" of Linq to SQL, i've found myself fighting with this issue (probably result of wrong use of it! :)) I've modified the entities auto-generated by the MSLinqToSqlGenerator, turning them into simpler POCOs, i've removed any events or interfaces from them, and replaced EntitySet with List (which appears to be well supported) This disables any deferred loading or change tracking capabilities, which in my scenario is a desired feature. The problem i had is this: Read More...
|
-
Hi, Here's the SQL code: Select LastSeqNumber , NextSeqNumber , FirstAvailable = LastSeqNumber + 1 , LastAvailable = NextSeqNumber - 1 , NumbersAvailable = NextSeqNumber - (LastSeqNumber + 1) from ( Select LastSeqNumber = (Select isnull(Max(Seq2.SeqNumber),0) as SeqNumber from #SequenceTable Seq2 where Seq2.SeqNumber 1 order by LastSeqNumber Thanks. Read More...
|
-
SQLMetal - Error DBML1055 DeleteOnNull I'm getting the following when I try to create the vb. Microsoft (R) Database Mapping Generator 2008 version 1.00.21022 for Microsoft (R) .NET Framework version 3.5 Copyright (C) Microsoft Corporation. All rights reserved. TestDB.dbml(8) : Error DBML1055: The DeleteOnNull attribute of the Association element 'FK_Component_Product_C' of the Type element 'COMPONENT' can only be true for singleton association members mapped to non-nullable foreign key columns. Read More...
|
-
I'm working on a project where I need to dynamically group multiple fields in data returned in a DataSet. It looks like it would be possible to do this using Dynamic LINQ, but I'm having a problem finding a good source for the .GroupBy syntax. Can anyone provide a basic example in VB.NET of using a DataSet and Dynamic LINQ to group multiple fields? I'm sorry I don't have a code example, but I'm really lost on this one. I appreciate any help you can provide. Read More...
|
-
Hi, Im trying to run the code below but keep running into this NotSupportedException. The resultToAdd Query is definately returning a value but evertime i try the line in bold i get the exception in the title. Any ideas why? The SomeTable.ID is definately of type int also. IQueryable resultToAdd = ( from h in db.SomeTable join a in db.AnotherTable on h.ID equals a.SomeTable_ID where a.ID == 15 select h).AsQueryable(); int x = resultToAdd.ElementAt(0).ID ; Cheers Read More...
|
-
Hello guys ! what about "in" in Linq ? Select * from mytable where mycolumn in (selec mycolum2 from mytable2) Is there any way to do this in Linq ? Thanks for your feedbacks ! Regards, Fabianus Read More...
|
-
I am playing about with LINQ and trying to learn Object Oriented programming. I have a database Interface class which will call an xmlClass or sqlClass. I am trying to write a method in the xmlClass/sqlClass which will return a LINQ query. Please see the following code:- Public Function GetAllWords() As Object Dim ds = _ From xWord In mWordList... WordList:WordList > _ Order By xWord. WordList:Word > . @ Name _ Select Name = xWord. WordList:Word > . @ Name, Picture = xWord. WordList:Word > . WordList:Picture Read More...
|
-
I have a keyword search that i want to convert to LINQ. The user has the option of choosing All words, Any word or Exact phrase. I can handle the All words or Exact phrase, but not the Any word. I've come to the conclusion that the extension - System.Linq.Dynamic doesn't support LIKE so i can't compose a string based qry with ORs using that. I came across the excellent PredicateBuilder at http://www.albahari.com/nutshell/predicatebuilder.html, but i've no idea how to use it with Visual Basic (The Read More...
|
-
I am writing some wrapper class such that it can be called as follow: NorthWindDataContext dc = new NorthWindDataContext(); Expression> predicate = (c => c.City == "london"); IOrderedQueryable orderby = dc.Customers.OrderBy(c => c.Country).ThenByDescending(c => c.ContactName); LINQSQL persistSQL = new PersistenceLINQSQL(predicate, orderby); Is there a way in the wrapper class to retrieve the dataContext given either predicate or orderby ? Thanks Read More...
|
-
Are there any work arounds for serializing DLinq object.as such when i'm trying it's giving me an error saying that EntitySet is not marked as serializable. Read More...
|
-
Looking at the code generated by the LINQ-to-SQL designer, I see that there is no PropertyChanged event fire when I add to or remove from an entity set. I.e. there is a PropertyChangING event fired for the change to the list contents (something added or removed) bu ther is no PropertyChangED. Is this a feature or a bug? John Read More...
|
-
I have the following Linq Query var results = from r in eventResults select new { r.EventID, r.EventDescription, r.ShipStartDate, r.ShipEndDate, r.EventTypeID, r.TotalEventCost, r.FixedAmount, VariableChecksPaid = checks.Where(x => x.EventID == r.EventID).Sum(x => x.VariableAmount), FixedChecksPaid = checks.Where(x => x.EventID == r.EventID).Sum(x => x.FixedAmount), VariableDeductionsCleared = deductions.Where(x => x.EventID == r.EventID).Sum(x => x.VariableAmount), FixedDeductionsCleared = deductions.Where(x Read More...
|
-
im new to c#..i only know the basics.. I need to develop a tool which collects system info (client side) and send it to a server periodically. For this..I am planning to use LINQ with services on client side 1. Is it feasible ? 2. Can I use Windows Services to begin the data collection process whenever required ? 3. Can forms be invoked using services ? Any suggestion/code snippets will be of utmost help...thank you Read More...
|
-
Just wondering if anyone knows that LINQ to XML uses to do the dynamic binding to WPF. I am assuming that insert/update/delete's are specifically handled on something like INotifyCollectionChanged (like ObservableCollection<>) - but I cannot see this implemented anywhere. I know the 'what' of binding - ie. how to use it, I want to know 'how' it works. Regards, Fil. Read More...
|
-
I am trying to port over some code to use LINQ to SQL. I create a LINQ to SQL class and seems to work fine for reading/writing data to the database. I am having trouble getting a stored procedure ( RetrieveSN ) to work. The older code is shown below and works. All it does is pass in a string value and creates a new serial number to return. IDbCommand cmd = _db.CreateCommand( "dbo.RetrieveSN" , true ); AddParameter(cmd, "Part" , Part); //AddParameter(cmd, "Number", ""); IDataReader reader = _db.ExecuteReader(cmd); Read More...
|
-
Now I'm creating two classes as entity which have on-to-many relationship like customer and order in northwind. First I created classes by hand.I wrote entityset property and relationship attribute. BuI encountered that the property for foreign key of child entity was not set when inserting. My code to insert entity to database is like below. customer.Orders.Add(order); With above code,new records for parent and child entitry were inserted to database,but field for foreign key was still null. So,I Read More...
|
-
I have an Sql Server database that contains a table for clients and a table for visits the clients make to the shop. The tables are indexed on the client table primary key ClientId. I used the linq to sql designer to create a data context, which produced all my business classes. The produced client class has a property EntitySet Visits. If I do something like (assume client "1" has no visits currently)... Code Snippet ClientDBContext db = new ClientDbContext(); Client client = db.Clients.Single(client Read More...
|
-
Hey, I hope someone can help me on this or give me some pointers. I have a function that returns an expression tree, like so: Code Snippet public class PublishableItem { // ... public static Expression> IsPublished() where T: PublishableItem { return i => i.State >= 1; } } When I use this function in a regular LINQ query, it works fine: Code Snippet IQueryable categories = (from c in db.Categories select c).Where(PublishableItem.IsPublished()); However, when I use the same function in a compiled Read More...
|
-
I'm want to display 3 fields in my combobox. I'm not sure how to select the fields. It only allows me to select one field (dpo_lname) that I know of. I want to select dpo_fname, dpo_badge . Can you help? Code below. var db = new dpoffassignedDataContext(); var q = from dpoff in db.SP_DpOffAssignedComboBox() select dpoff. dpo_fname ; foreach (var stuff in q) { comboBox6.Items.Add(stuff); } Thanks, Ron Read More...
|
-
Hello, I'm new to LINQ and I am trying to write a query using following list of elements (the list can have any type of objects): Code Snippet List list = new List() { "Elem 1", "Elem 2", "Elem 3", "Elem 4", "Elem 5", "Elem 6", "Elem 7", "Elem 8", "Elem 9", "Elem 10", "Elem 11","Elem 12", "Elem 13" }; I want to group the elements, but each group has to have 4 elements (the last one, the rest of elements). Could anyone help me ? Read More...
|
-
I have a table named Test with an autoincrement field name ID and a varchar field Name. I am trying to run this code: DataClasses1DataContext dc = new DataClasses1DataContext (); Test t = new Test { Name = "Test" }; dc.Tests.InsertAllOnS ubmit(t); dc.SubmitChanges(); And am getting this error: Error 53 The type arguments for method 'System.Data.Linq.Table.InsertAllOnSubmit(System.Collections.Generic.IEnumerable)' cannot be inferred from the usage. Try specifying the type arguments explicitly. I'm Read More...
|
-
What do I need to do to be able to store a list of entities in the asp.net viewstate? A simple: Code Snippet var query = from st in dc.SomeTables where st.foo = 'foo' select st; ViewState["Foo"] = st.ToList(); results in: System.Runtime.Serialization.SerializationException: Type 'SomeTable' in Assembly 'App_Code.corio68f, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable. at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType Read More...
|
-
|
The stridency and shrillness of the ant | |
|