views:

86

answers:

2
+2  Q: 

LINQ use with XML

Hi! We have a project in which access the DB layer (MS SQL) with LINQ. Can we now change our DB layer to XML file and still access it with the same LINQ?

We want add possibility to store data in a single XML file or a set of XML files.

Current LINQ to SQL code looks like:

result = (from e in db.Organizations
          where e.Id == idOrganization
          select e).SingleOrDefault();

or

 result = (from e in db.Organizations
           where e.Name.Trim().ToUpper() == organizationName.Trim().ToUpper()
               && e.Id!=idCurrentOrganization
           select e).Count()>0;
+2  A: 

LINQ to SQL and LINQ to XML have similarities, but they aren't identical. The LINQ queries could probably be written so that they could be used in the same way, but the code of the queries themselves would probably need to change.

Could you give some examples of what your current LINQ to SQL code looks like? Including examples of what kind of data you're using and how you want to format the XML would probably help people here give more specific pointers.

Edit: Your first query appears to return an object. If your LINQ to SQL and your LINQ to XML both return the same type, then you could swap them out without changing the code that consumes the result.

Your second query appears to return a bool, so the same concept applies to that one. Code elsewhere in your solution won't care how that bool was set.

Mike's suggestion of using an Interface for your data access layer is the way to go. For your 2 examples, you'd have an interface that contains an Organization object and a bool. Your SQL and XML implementations would be different, but every other part of your code would only need to know how to use the interface.

Dennis Palmer
Thank you. I will add details soon.
Sasha
+1  A: 

Hi,

There's an extra step you will have to do: you will have to load the XML into a XDocument (or a XNode if I recall correctly) before being able to query you data.

After that it's simply a matter of selecting nodes in a tree with LINQ to XML syntax.

Unfortunately, there is no LINQ syntax that will let you query both and let you plug the XML or the DB transparently.

PS. Pay attention to the XML namespace when you will select nodes, it could be a headache!

PS2. Sorry I don't have code handy

PS3. I would suggest your database layer to derive from an interface, that way you will be able to switch from XML to DB and vice-versa easily

Hope this helps

Mike Gleason jr Couturier
Thank you. I will try to do as you say in PS3
Sasha
You're more than welcome
Mike Gleason jr Couturier