Best linq questions in May 2011

Linq to XML Queries

6 votes

Hi All, Let's just say I have an XML file that looks like this:

<?xml version="1.0" encoding="utf-8"?>
<Customers>
  <Customer Name="Jason Voorhees" WeaponPurchased="Machette" SalePrice="499.90" />
  <Customer Name="Michael Myers" WeaponPurchased="Kitchen Knife" SalePrice="96.75" />
</Customers>

Is it possible, with Linq, to do something like this:?

foreach customer in Customers select WeaponPurchased where Name equals "Jason Voorhees"

or:

foreach customer in Customers select customer
label1.Text += "Name: " + customer.Name + Environment.NewLine + "WeaponPurchased: " + customer.WeaponPurchased;

I've seen this type of query before on MSDN, but the links in my favorites lead to the wrong page now, and I'm still trying to find these particular examples. Any help is much appreciated,

Thank you

Try this:

var doc = XDocument.Load(Path.Combine(path, "file.xml"));
var query = from c in doc.Descendants("Customer")
            where c.Attributes("Name").Single().Value == "Jason Voorhees"
            select c.Attributes("WeaponPurchased").Single().Value;

It will return IEnumerable<string> with names of weapons.

How to update a database with new information

4 votes

I am terrible with databases so please bear with me.

I have a program that gets some user information and adds it to a database table. I then later need to get more information for that table, and update it. To do so I have tried doing this:

    public static void updateInfo(string ID, string email, bool pub)
    {
        try
        {
            //Get new data context
            MyDataDataContext db = GetNewDataContext(); //Creates a new data context

            //Table used to get user information
            User user = db.Users.SingleOrDefault(x => x.UserId == long.Parse(ID));

            //Checks to see if we have a match
            if (user != null)
            {
                //Add values
                user.Email = email;
                user.Publish = publish;
            }

            //Prep to submit changes
            db.Users.InsertOnSubmit(user);
            //Submit changes
            db.SubmitChanges();
        }
        catch (Exception ex)
        {
            //Log error
            Log(ex.ToString());
        }
    }

But I get this error:

System.InvalidOperationException: Cannot add an entity that already exists.

I know this is because I already have an entry in the table, but I don't know how to edit the code to update, and not try to make a new one?

Why does this not work? Wouldn't submitting changes on a current item update that item and not make a new one?

The problem is

//Prep to submit changes
db.Users.InsertOnSubmit(user);

Because you got the user from the DB already, you don't need to re-associate it with the context.

Comment that out and you're good to go.

Just a style / usage comment as well. You should dispose your context:

public static void updateInfo(string ID, string email, bool pub)
{
    try
    {
        using (MyDataDataContext db = GetNewDataContext()) 
        {
            User user = db.Users.SingleOrDefault(x => x.UserId == long.Parse(ID));

            if (user != null)
            {
                user.Email = email;
                user.Publish = publish;
            }

            db.SubmitChanges();
        }
    }
    catch (Exception ex)
    {
        //Log error
        Log(ex.ToString());

        // TODO: Consider adding throw or telling the user of the error.
        // throw;

    }
}