How to update a number of Rows in a Table using Linq - linq-to-sql

I am using the following code to update the UserSession column of the Activities. Following code return the records if the ExpiryTimeStamp is less then current date.
Then it Update the UserSession column to 0 for the returned recods in the table.
.Now I wants that if there are 100 records are returned then these should update at one time instead of using the FoREach. Is it posible in Linq
CacheDataDataContext db = new CacheDataDataContext();
var data = (from p in db.Activities
where p.ExpiryTimeStamp < DateTime.Now
select p).ToList();
data.ForEach(ta => ta.UserSession = "0");
db.SubmitChanges();

In short, no: Linq-2-sql does not do batch updates out of the box.
(I am not sure your foreach will work like you wrote - i do not think so - but this is similar and will work)
foreach (var x in data)
{x.UserSession = "0";}
db.SubmitChanges()
BUT, even if you do it like this, Linq-2-sql will send an update statement for each record to the database. So with your example of 100 records returned you will get 100 individual updates send to the database.

Related

Does SQL Server CE require/provide an "UpdateOnSubmit()"?

To insert a record in SQL Server CE, you call ..InsertOnSubmit(), passing the class instance that represents the record being inserted, followed by .SubmitChanges();
Do I need a similar construct for updating a record? I've got this:
SQLCEDataContext sqlcedc = new SQLCEDataContext(SQLCEDataContext.DBConnectionString);
var invitations = (from SQLCEDataDefinition invitation in
sqlcedc.SQLCEDataDefinitions
where invitation.SenderID == senderID
select invitation).SingleOrDefault();
invitations.SenderDeviceID = senderDeviceID;
sqlcedc.SubmitChanges();
..but wonder if I need the analogue of InsertOnSubmit() - but there is no UpdateOnSubmit() that I can see. Do I need to user InsertOnSubmit() even though this is an Update operation,not an Insert operation?
windows-phone-8 sql-server-ce update linq
No you don't have an UpdateOnSubmit() and you can't use the InsertOnSubmit() to update your record.
You need to fetch the data first, update your property and then use the SubmitChanges()
Try like this:
SQLCEDataContext sqlcedc = new SQLCEDataContext(SQLCEDataContext.DBConnectionString);
var invitations = (from SQLCEDataDefinition invitation in
sqlcedc.SQLCEDataDefinitions
where invitation.SenderID == senderID
select invitation).SingleOrDefault();
invitations.SenderDeviceID = senderDeviceID;
sqlcedc.SubmitChanges();

Alternative way to do FirstOrDefault in LINQ

I've got a membership table that records whether a user is a member of a list. When an update to a user's membership occurs a new record is written and the previous records are left as is which allows a history of their memberships to be maintained. To get a user's membership status involves selecting their most recent entry.
An example of some user list membership data is below. The aim is to find a LINQ expression that groups by list and user but only returns the row with most recently inserted record.
List Name, Username, Comment, ExpiresOn, Inserted
Test List, joeb, second update, 2012-03-13 16:55:03, 2012-01-31 22:28:40
Test List, joeb, first update, 2012-02-13 16:55:01, 2012-01-31 22:28:39
Test List, joeb, initial, 2012-01-13 16:55:02, 2012-01-31 22:28:38
An SQL query illustrates how the current list membership status can be extracted.
select ulm2.ID, ulm2.ExpiresOn, ulm2.Comment, ulm2.Inserted
from UserListMembership as ulm1
left outer join UserListMembership ulm2 on ulm1.id = ulm2.id
group by ulm1.userlistid, ulm1.userid;
The question is how to write a LINQ expression for the query that doesn't use a nested FirstOrDefault call which causes my MySQL entity framework provider to throw a "System.NotSupportedException: Specified method is not supported." exception?
Update:
Below is my failing LINQ expression, it throws the "Specified method is not supported" once the FirstOrDefault call is added.
var query = from mem in db.UserListMemberships
where
mem.User.UserUsernames.Any(y => y.Username.ToLower() == username.ToLower())
&& mem.UserList.Account.Subscriptions.Any(x => x.ID == subscriptionID)
&& mem.ExpiresOn > utcNow
group mem by new { mem.UserListID, mem.UserID } into g
select new { UserListMembership = (from mem2 in db.UserListMemberships where mem2.UserListID == g.Key.UserListID && mem2.UserID == g.Key.UserID orderby mem2.Inserted descending select mem2).FirstOrDefault() };
return query.Select(a => a.UserListMembership).ToList();
Without posting code it's hard for anyone to see what your issue is.
Are you not able to just order the results by your date field and then select the first record? Something like users.OrderByDescending(u => u.Inserted).FirstOrDefault()?

Linq to Sql: Join, why do I need to load a collection

I have 2 tables that I need to load together all the time, the both must exist together in the database. However I am wondering why Linq to Sql demands that I have to load in a collection and then do a join, I only want to join 2 single tables where a record where paramid say = 5, example...
var data = _repo.All<TheData>(); //why do I need a collection/IQueryable like this?
var _workflow = _repo.All<WorkFlow>()
.Where(x => x.WFID== paramid)
.Join(data, x => x.ID, y => y.WFID, (x, y) => new
{
data = x,
workflow = y
});
I gues then I need to do a SingleOrDefault()? If the record is not null pass it back?
I Understand the Sql query comes out correctly, is there a better way to write this?
NOTE: I need to search a table called Participants to see if the loggedonuser can actually view this record, so I guess I should leave it as this? (this is main requirement)
var participant = _repo.All<Participants>();
.Any(x=> x.ParticipantID == loggedonuser.ID); //add this to above query...
The line var data = _repo.All<TheData>(); is something like saying 'start building query against the TheData table'.
This function returns you an IQueryable which will contain a definition of the query against your database.
So this doesn't mean you load the whole TheData table data with this line!
The query will be executed the moment you do something like .Count(), .Any(), First(), Single(), or ToList(). This is called deferred execution.
If you would end your query with SingleOrDefault() this will create a sql query that joins the two tables, add the filter and select the top most record or null(or throw an error if there are more!).
You could also use Linq instead of query extension methods.
It would look like:
var data = _repo.All<TheData>();
var _workflow = from w in _repo.All<WorkFlow>()
join t in _repo.All<TheData> on w.Id equals t.WFID
where x.WIFD = paramid
select new
{
data = t,
workflow = x
});

Could not format node 'Value' for execution as SQL

I've stumbled upon a very strange LINQ to SQL behaviour / bug, that I just can't understand.
Let's take the following tables as an example: Customers -> Orders -> Details.
Each table is a subtable of the previous table, with a regular Primary-Foreign key relationship (1 to many).
If I execute the follow query:
var q = from c in context.Customers
select (c.Orders.FirstOrDefault() ?? new Order()).Details.Count();
Then I get an exception: Could not format node 'Value' for execution as SQL.
But the following queries do not throw an exception:
var q = from c in context.Customers
select (c.Orders.FirstOrDefault() ?? new Order()).OrderDateTime;
var q = from c in context.Customers
select (new Order()).Details.Count();
If I change my primary query as follows, I don't get an exception:
var q = from r in context.Customers.ToList()
select (c.Orders.FirstOrDefault() ?? new Order()).Details.Count();
Now I could understand that the last query works, because of the following logic:
Since there is no mapping of "new Order()" to SQL (I'm guessing here), I need to work on a local list instead.
But what I can't understand is why do the other two queries work?!?
I could potentially accept working with the "local" version of context.Customers.ToList(), but how to speed up the query?
For instance in the last query example, I'm pretty sure that each select will cause a new SQL query to be executed to retrieve the Orders. Now I could avoid lazy loading by using DataLoadOptions, but then I would be retrieving thousands of Order rows for no reason what so ever (I only need the first row)...
If I could execute the entire query in one SQL statement as I would like (my first query example), then the SQL engine itself would be smart enough to only retrieve one Order row for each Customer...
Is there perhaps a way to rewrite my original query in such a way that it will work as intended and be executed in one swoop by the SQL server?
EDIT:
(longer answer for Arturo)
The queries I provided are purely for example purposes. I know they are pointless in their own right, I just wanted to show a simplistic example.
The reason your example works is because you have avoided using "new Order()" all together. If I slightly modify your query to still use it, then I still get an exception:
var results = from e in (from c in db.Customers
select new { c.CustomerID, FirstOrder = c.Orders.FirstOrDefault() })
select new { e.CustomerID, Count = (e.FirstOrder != null ? e.FirstOrder : new Order()).Details().Count() }
Although this time the exception is slightly different - Could not format node 'ClientQuery' for execution as SQL.
If I use the ?? syntax instead of (x ? y : z) in that query, I get the same exception as I originaly got.
In my real-life query I don't need Count(), I need to select a couple of properties from the last table (which in my previous examples would be Details). Essentially I need to merge values of all the rows in each table. Inorder to give a more hefty example I'll first have to restate my tabels:
Models -> ModelCategoryVariations <- CategoryVariations -> CategoryVariationItems -> ModelModuleCategoryVariationItemAmounts -> ModelModuleCategoryVariationItemAmountValueChanges
The -> sign represents a 1 -> many relationship. Do notice that there is one sign that is the other way round...
My real query would go something like this:
var q = from m in context.Models
from mcv in m.ModelCategoryVariations
... // select some more tables
select new
{
ModelId = m.Id,
ModelName = m.Name,
CategoryVariationName = mcv.CategoryVariation.Name,
..., // values from other tables
Categories = (from cvi in mcv.CategoryVariation.CategoryVariationItems
let mmcvia = cvi.ModelModuleCategoryVariationItemAmounts.SingleOrDefault(mmcvia2 => mmcvia2.ModelModuleId == m.ModelModuleId) ?? new ModelModuleCategoryVariationItemAmount()
select new
{
cvi.Id,
Amount = (mmcvia.ModelModuleCategoryVariationItemAmountValueChanges.FirstOrDefault() ?? new ModelModuleCategoryVariationItemAmountValueChange()).Amount
... // select some more properties
}
}
This query blows up at the line let mmcvia =.
If I recall correctly, by using let mmcvia = new ModelModuleCategoryVariationItemAmount(), the query would blow up at the next ?? operand, which is at Amount =.
If I start the query with from m in context.Models.ToList() then everything works...
Why are you looking into only the individual count without selecting anything related to the customer.
You can do the following.
var results = from e in
(from c in db.Customers
select new { c.CustomerID, FirstOrder = c.Orders.FirstOrDefault() })
select new { e.CustomerID, DetailCount = e.FirstOrder != null ? e.FirstOrder.Details.Count() : 0 };
EDIT:
OK, I think you are over complicating your query.
The problem is that you are using the new WhateverObject() in your query, T-SQL doesnt know anyting about that; T-SQL knows about records in your hard drive, your are throwing something that doesn't exist. Only C# knows about that. DON'T USE new IN YOUR QUERIES OTHER THAN IN THE OUTER MOST SELECT STATEMENT because that is what C# will receive, and C# knows about creating new instances of objects.
Of course is going to work if you use ToList() method, but performance is affected because now you have your application host and sql server working together to give you the results and it might take many calls to your database instead of one.
Try this instead:
Categories = (from cvi in mcv.CategoryVariation.CategoryVariationItems
let mmcvia =
cvi.ModelModuleCategoryVariationItemAmounts.SingleOrDefault(
mmcvia2 => mmcvia2.ModelModuleId == m.ModelModuleId)
select new
{
cvi.Id,
Amount = mmcvia != null ?
(mmcvia.ModelModuleCategoryVariationItemAmountValueChanges.Select(
x => x.Amount).FirstOrDefault() : 0
... // select some more properties
}
Using the Select() method allows you to get the first Amount or its default value. I used "0" as an example only, I dont know what is your default value for Amount.

Populate JOIN into a list in one database query

I am trying to get the records from the 'many' table of a one-to-many relationship and add them as a list to the relevant record from the 'one' table.
I am also trying to do this in a single database request.
Code derived from Linq to Sql - Populate JOIN result into a List almost achieves the intended result, but makes one database request per entry in the 'one' table which is unacceptable. That failing code is here:
var res = from variable in _dc.GetTable<VARIABLE>()
select new { x = variable, y = variable.VARIABLE_VALUEs };
However if I do a similar query but loop through all the results, then only a single database request is made. This code achieves all goals:
var res = from variable in _dc.GetTable<VARIABLE>()
select variable;
List<GDO.Variable> output = new List<GDO.Variable>();
foreach (var v2 in res)
{
List<GDO.VariableValue> values = new List<GDO.VariableValue>();
foreach (var vv in v2.VARIABLE_VALUEs)
{
values.Add(VariableValue.EntityToGDO(vv));
}
output.Add(EntityToGDO(v2));
output[output.Count - 1].VariableValues = values;
}
However the latter code is ugly as hell, and it really feels like something that should be do-able in a single linq query.
So, how can this be done in a single linq query that makes only a single database query?
In both cases the table is set to preload using the following code:
_dc = _db.CreateLinqDataContext();
var loadOptions = new DataLoadOptions();
loadOptions.LoadWith<VARIABLE>(v => v.VARIABLE_VALUEs);
_dc.LoadOptions = loadOptions;
I am using .NET 3.5, and the database back-end was generated using SqlMetal.
This link may help
http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
Look under join operators. You'll probably have to change from using extension syntax other syntax too. Like this,
var = from obj in dc.Table
from obj2 in dc.Table2
where condition
select