Search Results

Search found 19804 results on 793 pages for 'linq to xml'.

Page 8/793 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Linq to sql Error "Data at the root level is invalid " for nullable xml column

    - by Mukesh
    I have Created a table like CREATE TABLE [dbo].[tab1]( [Id] [int] NOT NULL, [Name] [varchar](100) NOT NULL, [Meta] [xml] NULL, CONSTRAINT [PK_tab1] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] When I am doing linq to sql query to fetch a data it throw an error "data at the root level is invalid linq". In further investigation I come to know that the meta column is null in that case. In real it is nullable Do I have to remove the nullable and set some blank root node as default or there is some another way to get rid of the error. My linq Query which throws error var obj1= (from obj in dbContext.tab1s where obj.id== 123 select obj).FirstOrDefault<Tab1>();

    Read the article

  • LINQ To SQL exception: Local sequence cannot be used in LINQ to SQL implementation of query operator

    - by pcampbell
    Consider this LINQ To SQL query. It's intention is to take a string[] of search terms and apply the terms to a bunch of different fields on the SQL table: string[] searchTerms = new string[] {"hello","world","foo"}; List<Cust> = db.Custs.Where(c => searchTerms.Any(st => st.Equals(c.Email)) || searchTerms.Any(st => st.Equals(c.FirstName)) || searchTerms.Any(st => st.Equals(c.LastName)) || searchTerms.Any(st => st.Equals(c.City)) || searchTerms.Any(st => st.Equals(c.Postal)) || searchTerms.Any(st => st.Equals(c.Phone)) || searchTerms.Any(st => c.AddressLine1.Contains(st)) ) .ToList(); An exception is raised: Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator Question: Why is this exception raised, and how can the query be rewritten to avoid this exception?

    Read the article

  • SSIS - XML Source Script

    - by simonsabin
    The XML Source in SSIS is great if you have a 1 to 1 mapping between entity and table. You can do more complex mapping but it becomes very messy and won't perform. What other options do you have? The challenge with XML processing is to not need a huge amount of memory. I remember using the early versions of Biztalk with loaded the whole document into memory to map from one document type to another. This was fine for small documents but was an absolute killer for large documents. You therefore need a streaming approach. For flexibility however you want to be able to generate your rows easily, and if you've ever used the XmlReader you will know its ugly code to write. That brings me on to LINQ. The is an implementation of LINQ over XML which is really nice. You can write nice LINQ queries instead of the XMLReader stuff. The downside is that by default LINQ to XML requires a whole XML document to work with. No streaming. Your code would look like this. We create an XDocument and then enumerate over a set of annoymous types we generate from our LINQ statement XDocument x = XDocument.Load("C:\\TEMP\\CustomerOrders-Attribute.xml");   foreach (var xdata in (from customer in x.Elements("OrderInterface").Elements("Customer")                        from order in customer.Elements("Orders").Elements("Order")                        select new { Account = customer.Attribute("AccountNumber").Value                                   , OrderDate = order.Attribute("OrderDate").Value }                        )) {     Output0Buffer.AddRow();     Output0Buffer.AccountNumber = xdata.Account;     Output0Buffer.OrderDate = Convert.ToDateTime(xdata.OrderDate); } As I said the downside to this is that you are loading the whole document into memory. I did some googling and came across some helpful videos from a nice UK DPE Mike Taulty http://www.microsoft.com/uk/msdn/screencasts/screencast/289/LINQ-to-XML-Streaming-In-Large-Documents.aspx. Which show you how you can combine LINQ and the XmlReader to get a semi streaming approach. I took what he did and implemented it in SSIS. What I found odd was that when I ran it I got different numbers between using the streamed and non streamed versions. I found the cause was a little bug in Mikes code that causes the pointer in the XmlReader to progress past the start of the element and thus foreach (var xdata in (from customer in StreamReader("C:\\TEMP\\CustomerOrders-Attribute.xml","Customer")                                from order in customer.Elements("Orders").Elements("Order")                                select new { Account = customer.Attribute("AccountNumber").Value                                           , OrderDate = order.Attribute("OrderDate").Value }                                ))         {             Output0Buffer.AddRow();             Output0Buffer.AccountNumber = xdata.Account;             Output0Buffer.OrderDate = Convert.ToDateTime(xdata.OrderDate);         } These look very similiar and they are the key element is the method we are calling, StreamReader. This method is what gives us streaming, what it does is return a enumerable list of elements, because of the way that LINQ works this results in the data being streamed in. static IEnumerable<XElement> StreamReader(String filename, string elementName) {     using (XmlReader xr = XmlReader.Create(filename))     {         xr.MoveToContent();         while (xr.Read()) //Reads the first element         {             while (xr.NodeType == XmlNodeType.Element && xr.Name == elementName)             {                 XElement node = (XElement)XElement.ReadFrom(xr);                   yield return node;             }         }         xr.Close();     } } This code is specifically designed to return a list of the elements with a specific name. The first Read reads the root element and then the inner while loop checks to see if the current element is the type we want. If not we do the xr.Read() again until we find the element type we want. We then use the neat function XElement.ReadFrom to read an element and all its sub elements into an XElement. This is what is returned and can be consumed by the LINQ statement. Essentially once one element has been read we need to check if we are still on the same element type and name (the inner loop) This was Mikes mistake, if we called .Read again we would advance the XmlReader beyond the start of the Element and so the ReadFrom method wouldn't work. So with the code above you can use what ever LINQ statement you like to flatten your XML into the rowsets you want. You could even have multiple outputs and generate your own surrogate keys.        

    Read the article

  • Check username and password in LINQ query

    - by b0x0rz
    this linq query var users = from u in context.Users where u.UserEMailAdresses.Any(e1 => e1.EMailAddress == userEMail) && u.UserPasswords.Any(e2 => e2.PasswordSaltedHash == passwordSaltedHash) select u; return users.Count(); returns: 1 even when there is nothing in password table. how come? what i am trying to do is get the values of email and passwordHash from two separate tables (UserEMailAddresses and UserPasswords) linked via foreign keys to the third table (Users). it should be simple - checking if email and password mach from form to database. but it is not working for me. i get 1 (for count) even when there are NO entries in the UserPasswords table. is the linq query above completely wrong, or...?

    Read the article

  • Entity LINQ on many-to-many got error "LINQ to Entities does not recognize the method 'Boolean Conta

    - by user300992
    I have 2 tables (Users and Roles) they are mapped as Many-to-Many in relational db. When I imported to Entity Data Content, they are still staying as the same relationship. Since they are mapped as Many-To-Many in Entity, I can access Users.RoleCollection or Roles.UserCollection However, when I execute this LINQ query, I got "LINQ to Entities does not recognize the method 'Boolean Contains... method, and this method cannot be translated into a store expression." var result (from a in Users from b in Roles where a.RoleCollection.Contains(b) select a); I think I must did something wrong... please help.

    Read the article

  • Search XDocument with LINQ with out knowing the Namespace

    - by BarDev
    Is there a way to search a XDocument without knowing the Namespace. I have a process that logs all soap requests and encrypts the sensitive data. I want to find any elements based on name. Something like, give me all elements where the name is CreditCard. I don't care what the namespace is. My problem seems to be with LINQ and requiring a xml namespace. I have other processes that retrieve values from XML, but I know the namespace for these other process. XDocument xDocument = XDocument.Load(@"C:\temp\Packet.xml"); XNamespace xNamespace = "http://CompanyName.AppName.Service.Contracts"; var elements = xDocument.Root.DescendantsAndSelf().Elements().Where(d = d.Name == xNamespace + "CreditCardNumber"); But what I really want, is to have the ability to search xml without knowing about namespaces, something like this: XDocument xDocument = XDocument.Load(@"C:\temp\Packet.xml"); var elements = xDocument.Root.DescendantsAndSelf().Elements().Where(d = d.Name == "CreditCardNumber") But of course this will not work be cause I do no have a namespace. BarDev

    Read the article

  • help converting sql to linq expression with count

    - by Philip
    I am trying to convert the following SQL into a LINQ expression SELECT COUNT(ID) AS Count, MyCode FROM dbo.Archive WHERE DateSent=@DateStartMonth AND DateSent<=@DateEndMonth GROUP BY MyCode and I have been trying to follow this webpage as an example http://stackoverflow.com/questions/606124/converting-sql-containing-top-count-group-and-order-to-linq-2-entities I got this so far but I am stuck on understanding the new part var res=(from p in db.Archives where (p.DateSent>= dateStartMonth) && (p.DateSent< dateToday) group p by p.MyCode into g select new { ??????MyCode = g.something?, MonthlyCount= g.Count() }); Thanks in advance for helping greatly appreciated Philip

    Read the article

  • Linq to SQL problem

    - by Ronnie Overby
    I have a local collection of recordId's (integers). I need to retrieve records that have every one of their child records' ids in that local collection. Here is my query: public List<int> OwnerIds { get; private set; } ... filteredPatches = from p in filteredPatches where OwnerIds.All(o => p.PatchesOwners.Select(x => x.OwnerId).Contains(o)) select p; I am getting this error: Local sequence cannot be used in Linq to SQL implementation of query operators except the Contains() operator. I get that .All() isn't supported by Linq to SQL, but is there a way to do what I am trying to do?

    Read the article

  • LINQ query checks for null

    - by user300992
    I have a userList, some users don't have a name (null). If I run the first LINQ query, I got an error saying "object reference not set to an instance of an object" error. var temp = (from a in userList where ((a.name == "john") && (a.name != null)) select a).ToList(); However, if I switch the order by putting the checking for null in front, then it works without throwing any error: var temp = (from a in userList where ((a.name != null) && (a.name == "john")) select a).ToList(); Why is that? If that's pure C# code (not LINQ), I think both would be the same. I don't have SQL profiler, I am just curious what will be the difference when they are being translated on SQL level.

    Read the article

  • Linq insert statement inserts nothing, does not fail either

    - by pietjepoeier
    I am trying to insert a new account in my Acccounts table with linq. I tried using the EntityModel and Linq2Sql. I get no insert into my database nor an exception of any kind. public static Linq2SQLDataContext dataContext { get { return new Linq2SQLDataContext(); } } try { //EntityModel Accounts acc = Accounts.CreateAccounts(0, Voornaam, Straat, Huisnummer, Stad, Land, 15, EmailReg, Password1); Entities.AddToAccounts(acc); Entities.SaveChanges(); //Linq 2 SQL Account account = new Account { City = Stad, Country = Land, EmailAddress = EmailReg, Name = Voornaam, Password = Password1, Street = Straat, StreetNr = Huisnummer, StreetNrAdd = Toevoeging, Points = 25 }; dataContext.Accounts.InsertOnSubmit(account); var conf = dataContext.ChangeConflicts; // No changeConflicts ChangeSet set = dataContext.GetChangeSet(); // 0 inserts, 0 updates, 0 deletes try { dataContext.SubmitChanges(); } catch (Exception ex) { } } catch (EntityException ex) { }

    Read the article

  • Changing an extention method from linq-to-sql to entity framework

    - by Jova
    I'm changing my project from working with Linq-to-SQL to working with Entity Framework. I have some extention methods that extend the classes created by LINQ and I'm wondering how to change them to work with the entities instead Here's an example. public static int GetPublishedArticlesCount(this Table<Article> source) { return GetPublishedArticles(source.Context as DataContext, null).Count(); } This method gets the number of published articles. Instead of using this Table<Article>, what should I use instead?

    Read the article

  • How to dynamically choose two fields from a Linq query as a result

    - by Dr. Zim
    If you have a simple Linq query like: var result = from record in db.Customer select new { Text = record.Name, Value = record.ID.ToString() }; which is returning an object that can be mapped to a Drop Down List, is it possible to dynamically specify which fields map to Text and Value? Of course, you could do a big case (switch) statement, then code each Linq query separately but this isn't very elegant. What would be nice would be something like: (pseudo code) var myTextField = db.Customer["Name"]; // Could be an enumeration?? var myValueField = db.Customer["ID"]; // Idea: choose the field outside the query var result = from record in db.Customer select new { Text = myTextField, Value = myValueField };

    Read the article

  • Linq to Sql Projection Help

    - by Micah
    I've reached the end of my Linq rope. Need your help! Heres my table structure first(all linq to sql objects): InventoryItems -ID -AmtInStock IventoryKits -ID InventoryKits_to_InventoryItems -InventoryItemID -InventoryKitID So i need to do a projection like the following var q2=from k in GetAllKits()//returns IQueryable<InventoryKit> select new VMPublication()//ViewModel Object { ID = k.ID, Name = k.Name, WebAmountInStock = ,//need to get the Min() AmtInStock from InventoryItems here ItemCode = k.ItemCode, WebAmountOrdered = k.AmtOrdered.ToString(), WebReminderAmount = "", WebAmountWarning="", Type = "Kit" }; i have no idea how to get that Min() of InventoryItem's AmtInStock in that query. Please help! Very Appreciated!

    Read the article

  • Case insensitive string compare in LINQ-to-SQL

    - by BlueMonkMN
    I've read that it's unwise to use ToUpper and ToLower to perform case-insensitive string comparisons, but I see no alternative when it comes to LINQ-to-SQL. The ignoreCase and CompareOptions arguments of String.Compare are ignored by LINQ-to-SQL (if you're using a case-sensitive database, you get a case-sensitive comparison even if you ask for a case-insensitive comparison). Is ToLower or ToUpper the best option here? Is one better than the other? I thought I read somewhere that ToUpper was better, but I don't know if that applies here. (I'm doing a lot of code reviews and everyone is using ToLower.) Dim s = From row In context.Table Where String.Compare(row.Name, "test", StringComparison.InvariantCultureIgnoreCase) = 0 This translates to an SQL query that simply compares row.Name with "test" and will not return "Test" and "TEST" on a case-sensitive database.

    Read the article

  • How to update an element with a List using LINQ and C#

    - by Addie
    I have a list of objects and I'd like to update a particular member variable within one of the objects. I understand LINQ is designed for query and not meant to update lists of immutable data. What would be the best way to accomplish this? I do not need to use LINQ for the solution if it is not most efficient. Would creating an Update extension method work? If so how would I go about doing that? EXAMPLE: (from trade in CrudeBalancedList where trade.Date.Month == monthIndex select trade).Update( trade => trade.Buy += optionQty);

    Read the article

  • Using LINQ-To-Entities to Generate Information

    - by parminder
    I am working on a website where a user can add tags to their posted books, much like is currently done for questions on Stack Overflow. Classes: Books { bookId, Title } Tags { Id Tag } BooksTags { Id BookId TagId } Here are few sample records. Books BookId Title 113421 A 113422 B Tags Id Tag 1 ASP 2 C# 3 CSS 4 VB 5 VB.NET 6 PHP 7 java 8 pascal BooksTags Id BookId TagId 1 113421 1 2 113421 2 3 113421 3 4 113421 4 5 113422 1 6 113422 4 7 113422 8 Questions I need to write something in LINQ to entity queries which gives me data according to the tags: Query: bookIds where tagid = 1 Returns: bookid: 113421, 113422 Query 2: tags 1 and 2 Returns: 113421 I need tags and their count to to show in related tags, so in first case my related tags class should have following result. RelatedTags Tag Count 2 1 3 1 4 2 8 1 Second Case: RelatedTags Tag Count 3 1 4 1 How do I do this in LINQ?

    Read the article

  • Use LINQ and C# to make a new List from an old List

    - by Addie
    This should be pretty simple, but I am new at LINQ. I have a List of FillList structs. I'd like to use LINQ to create a new List where instead of having the number of buys and sells, I would have one variable containing the sum. For example, if the FillStruct structure has buy = 4 and sell = 2 then the NewFillStruct structure will have numlong = 2. If the FillStruct structure has buy = 2 and sell = 4 then the NewFillStruct structure will have numlong = -2. Here are the structures. struct FillStruct { int buy; int sell; string date; } struct NewFillStruct { int numlong; string date; }

    Read the article

  • Can't enumerate LinQ results with left join

    - by nvtthang
    var itemSet = from item in da.GetList<Models.account>() join file in objFileStorageList on item.account_id equals file.parent_id into objFile from fileItem in objFile.DefaultIfEmpty() where item.company != null && item.company.company_id == 123 orderby item.updatedDate descending select new { Id = item.account_id, RefNo = item.refNo, StartDate = item.StartDate , EndDate = item.EndDate , Comment = item.comment, FileStorageID = fileItem != null ? fileItem.fileStorage_id : -1, Identification = fileItem != null ? fileItem.identifier : null, fileName = fileItem != null ? fileItem.file_nm : null }; It raises error message when I try to enumerate through collection result from Linq query above. LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable1[SCEFramework.Models.fileStorage] DefaultIfEmpty[fileStorage](System.Collections.Generic.IEnumerable1[SCEFramework.Models.fileStorage])' method, and this method cannot be translated into a store expression foreach (var item in itemSet) { string itemRef= item.RefNo; } Please suggest me any solutions. Thanks in advance.

    Read the article

  • username and password check linq query in c#

    - by b0x0rz
    this linq query var users = from u in context.Users where u.UserEMailAdresses.Any(e1 => e1.EMailAddress == userEMail) && u.UserPasswords.Any(e2 => e2.PasswordSaltedHash == passwordSaltedHash) select u; return users.Count(); returns: 1 even when there is nothing in password table. how come? what i am trying to do is get the values of email and passwordHash from two separate tables (UserEMailAddresses and UserPasswords) linked via foreign keys to the third table (Users). it should be simple - checking if email and password mach from form to database. but it is not working for me. i get 1 (for count) even when there are NO entries in the UserPasswords table. is the linq query above completely wrong, or...?

    Read the article

  • Building 'flat' rather than 'tree' LINQ expressions

    - by Ian Gregory
    I'm using some code (available here on MSDN) to dynamically build LINQ expressions containing multiple OR 'clauses'. The relevant code is var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue)))); var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal)); This generates a LINQ expression that looks something like this: (((((ID = 5) OR (ID = 4)) OR (ID = 3)) OR (ID = 2)) OR (ID = 1)) I'm hitting the recursion limit (100) when using this expression, so I'd like to generate an expression that looks like this: (ID = 5) OR (ID = 4) OR (ID = 3) OR (ID = 2) OR (ID = 1) How would I modify the expression building code to do this?

    Read the article

  • How to order the items in a nested LINQ-provided collection

    - by Carson McComas
    I've got a (SQL Server) database table called Category. And another database table called SubCategory. SubCategory has a foreign key relationship to Category. Because of this, thanks to LINQ, each Cateogory has a property called SubCategories and LINQ is nice enough to return all the SubCategories associated with my Category when I grab it. If I want to sort the Categories alphabetically, I can just do: return db.Categories.OrderBy(c => c.Name); However, I have no idea how to order the SubCategories collection inside each Category. My goal is to return a collection of Categories, where all of the SubCategory collections inside of them are ordered alphabetically by Name.

    Read the article

  • Convert SQL to LINQ to SQL

    - by Adam
    Hi I have the SQL query with c as ( select categoryId,parentId, name,0 as [level] from task_Category b where b.parentId is null union all select b.categoryId,b.parentId,b.name,[level] + 1 from task_Category b join c on b.parentId = c.categoryId) select name,[level],categoryId,parentId as item from c and I want to convert it to LINQ to SQL, yet my LINQ skills are not there yet. Could someone please help me convert this. It's the with and union statements that are making this a bit more complex for me. Any help appreciated.

    Read the article

  • LINQ Equivalent query

    - by GilliVilla
    I have a List<string> List<string> students; students.Add("123Rob"); students.Add("234Schulz"); and a Dictionary<string,string> Dictionary<string, string> courses = new Dictionary<string, string>(); courses .Add("Rob", "Chemistry"); courses .Add("Bob", "Math"); courses .Add("Holly", "Physics"); courses .Add("Schulz", "Botany"); My objective now is to get a List with the values - {Chemistry,Botany} . In other words, I am trying to get the LINQ equivalent of select value from [courses] where [courses].key in ( select [courses].key from courses,students where [students].id LIKE '%courses.key%' ) How should the LINQ query be framed?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >