tags:

views:

47

answers:

1

So I have the following code:

// Get the current user
_currentUser = WindowsIdentity.GetCurrent();

// Get the list of address for the current user
_dataMap = new DataMapDataContext();
_addresses = _dataMap.Addresses
         .Where(address => address.InsertUserName == _currentUser.Name).ToList();

....

_addresses.Add(form.Item);
_dataMap.SubmitChanges();

When I call SubmitChanges nothing is saved in the database. Why is that? Am I missing the point? I thought with linq to sql you could just add items to your query results and then call SubmitChanges and it will work.... Clearly I am missing something.

Does it now work if you use "ToList"? If not then how do you insert stuff into the collection? (I don't think Add is part of IQueryable.)

+5  A: 

Dont use _addresses.Add

You can't add directly to an IQueryable, you need to add it to the entity set.

Try this:

    _dataMap.Addresses.InsertOnSubmit(form.Item);
    _dataMap.SubmitChanges();

Of course, i can't see what form.Item is, but be aware it needs to be of the same Entity type as the _dataMap.Addresses entity set.

It makes no difference if you use .ToList().

With LINQ-SQL (unless you're using some sort of POCO mapping), you can't add items to a collection/query, you need to add the item directly into the Entity Set for the specified Data Context.

You can call .InsertOnSubmit as many times as you like, and .SubmitChanges will push all those INSERT's to the DB for you.

More info on InsertOnSubmit here.

RPM1984