I have a sports database with a table groupmembers which have the fields ID, groupID and memberID. I get the memberID from a textbox called txtRemoveGroupMember and the groupID from a checkboxlist. Now I want to delete the rows which have both the groupID and the memberID.
I have tried this code:
foreach(ListItem listItem in cblRemoveMemberFromGroup.Items)
{
int memberid = Convert.ToInt32(txtRemoveGroupMember.Text);
int groupid = Convert.ToInt32(listItem.Value);
var removeFromGroup = from gm in dataContext.GroupMembers
where (gm.memberID == memberid) && (gm.groupID == groupid)
select gm;
dataContext.GroupMembers.DeleteOnSubmit(removeFromGroup);
dataContext.SubmitChanges();
}
But I get this error:
Error 7 Argument 1: cannot convert from 'System.Linq.IQueryable<GSI_side.GroupMember>' to 'GSI_side.GroupMember'
And this error:
Error 6 The best overloaded method match for 'System.Data.Linq.Table<GSI_side.GroupMember>.DeleteOnSubmit(GSI_side.GroupMember)' has some invalid arguments
Hope someone can help me figure this out!
You have to call .ToList()
var items = removeFromGroup.ToList();
foreach (var item in items)
dataContext.GroupMembers.DeleteOnSubmit(item);
For batch deletes I use this, because LINQ to SQL first loads the entire data which is going to be deleted, then it does the deletes each by each.
https://terryaney.wordpress.com/2008/04/14/batch-updates-and-deletes-with-linq-to-sql/
https://github.com/longday/LINQ-to-SQL-Batch-Updates-Deletes
removeFromGroup is still of type IQuerable.
You need to specify an actual GroupMember to delete.
You could use
GroupMember removeFromGroup = (from gm in dataContext.GroupMembers
where (gm.memberID == memberid) && (gm.groupID == groupid)
select gm).SingleOrDefault();
dataContext.GroupMembers.DeleteOnSubmit(removeFromGroup);
dataContext.SubmitChanges();
Alternatively, if your query returns a collection (from the looks of it, it won't since you are filtering by memberId) you could use
List<GroupMember> removeFromGroup = (from gm in dataContext.GroupMembers
where (gm.memberID == memberid) && (gm.groupID == groupid)
select gm).ToList();
dataContext.GroupMembers.DeleteAllOnSubmit(removeFromGroup);
dataContext.SubmitChanges();
var listToRemove=(from a in DB.Table
where a.Equals(id)
select a).ToList();
DB.Table.DeleteAllOnSubmit(listToRemove);
DB.SubmitChanges();
Related
I have two tables. Customer and CustomerBenefits.
Fields in each table
Customer - ID, Name, Address, Country etc
CUstomerBenefits - CustomerID, BenefitID (Both IDs have a relation to their relevant tables)
I am trying to list the customers and get the Benefit Details
IEnumerable<CustomerBenefit> GetData = from c in MyContext.CUstomerBenefits
where c.CustomerId == UserId & c.Active = true
orderby c.CustomerBenefit.BenType descending
select new {???? };
For the Select, Ive tried
select new {c.Benefit.Name }
but get the error
Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)
If i change IEnumerable<CustomerBenefit> to IEnumerable<dynamic> i get no errors but when the data is bound to my gridview i get the error that a field is not found.
How could i keep IEnumerable<CustomerBenefit> and select the columns i require?
You wrote:
CUstomerBenefits - CustomerID, BenefitID (Both IDs have a relation to
their relevant tables)
I interpret this as meaning that there is a table CustomerBenefit that contains, well, benefits and that the CUstomerBenefits table in turn is a link between the customer and the benefits. And now you want to get a list of all the benefits that a specific customer has?
This should do the trick:
IEnumerable<CustomerBenefit> GetData =
from c in MyContext.CUstomerBenefits
where c.CustomerId == UserId && c.Active == true
orderby c.CustomerBenefit.BenType descending
select c.CustomerBenefit;
Use: select c to get all of the column values or:
select new CustomerBenefit {CustomerID = c.CustomerID}; etc
var HOQuotePremiums = (from holoc in objRes.ResHO.HOLocations
from cst in ((HOLocation)holoc).HOBuildings
select new
{
RequestId = cst.HOPremium.RequestId,
BasePremium = Convert.ToInt32(cst.HOPremium.BasePremium),
PersonalLiabilityPremium = cst.HOPremium.PersonalLiabilityPremium,
MedicalPaymentPremium = cst.HOPremium.MedicalPaymentPremium,
FinalPremium = objRes.ResHO.FinalPremium,
WithoutAOPDeductibleFinalPremium = cst.HOPremium.WithoutAOPDeductibleFinalPremium,
SubTotalPremium = objRes.ResHO.FinalPremiumWithoutFeeTax,
LocationID = holoc.LocationID,
BuildingID = cst.BuildingID,
IsMinimumPremium = cst.HOPremium.IsMinimumPremium,
MinimumPremium = cst.HOPremium.MinimumPremium,
SubTotalPremiumWithoutMinimumPremium = cst.HOPremium.SubTotalPremiumWithoutMinimumPremium,
FinalRate=cst.HOPremium.FinalRate,
}).ToList();
Please try this .
I want to update one column in sql.in where condition two column names are there.
below is mu update query:
string sql = "UPDATE contact set ContactName=#ContactName where ContactID=#ContactId AND UserID=#Userid";
now I want to write using linq.How to write above query using linq.please help me.I tried
var updatequery = (from x in obj.Contacts where x.ContactID == ContactID select x).First();
updatequery.ContactName = ContactName;
obj.SubmitChanges();
but in the above query where condition having only one column name.I want to where condition having two column names.Thanks in advance.
You just have to use the conditional-AND operator &&:
var updateContacts = from x in obj.Contacts
where x.ContactID == ContactID && x.SecondColumn == SecondValue
select x;
// now use First or a loop if you expect multiple
foreach(var contact in updateContacts)
contact.ContactName = ContactName;
obj.SubmitChanges();
I don't know if this will help but you can try this as well.
var updatequery = obj.Contacts
.Where(x => x.ContactID == ContactID && x.SecondColumn == SecondValue)
.FirstOrDefault();
updatequery.ContactName = ContactName;
obj.SubmitChanges();
There is table ViewRight in my database with three columns:
user_id (FK- int)
folder_id(PK-int)
folder_name(varchar(MAX))
I wrote query in c# code to get values of table. I wrote this query below to get values from
ViewRight table of provided user_id.
var query2 = from p in dbContext.ViewRights where p.user_id==user_id select p;
Question I have to use foreach loop to get value of folder_id value of and folder_name of provided user_id. this foreach loop has single value. I don't want to use foreach loop for single value. I there any other approach to get this without using foreach loop.
var vr = query2.SingleOrDefault(x => x.user_id == userid);
if (vr != null)
{
Console.WriteLine(vr.folder_id);
}
Use var vr = query2.SingleOrDefault(x => x.user_id == userid);
if(vr != null) Console.WriteLine(vr.folder_id);
I can't believe John Saunders just copied my answer!
If there is only gonna be one record returned. var query2 = (from p in dbContext.ViewRights where p.user_id==user_id select p).FirstOrDefault();
.SingleOrDefault will get one or more count records
use
.FirstOrDefault();
i chose .FirstOrDefault
I'm using Entity Framework in order to connect to MySQL.
I have an incremental data which implements subversion technique. Each set of subversion record has the same LinkedId and separated by UpdatedTime.
My expectation is getting the latest version of each record from database. Thus, I write a linq statement like below:
public List<Entry> LoadFinalEntries(int rptId) {
return (from ent in ctx.Entries
where ent.ReportId == rptId
orderby ent.LinkedId, ent.UpdatedTime descending
group ent by ent.LinkedId into svnEnt
select svnEnt.FirstOrDefault()).ToList();
}
But at the run-time, it throws an EntityCommandCompilationException telling that "Specified method is not supported.". I know that method is FirstOrDefault, but cannot find anyway to fix it.
Please help me to find out another way to do.
What do you think using inner query?
return (from ent in ctx.Entries
where ent.ReportId == rptId &&
ent.UpdatedTime ==
(from inner in ctx.Entries
where inner.LinkedId == ent.LinkedId &&
inner.ReportId == rptId
select inner.UpdatedTime).Max()
select ent).ToList();
I've found a better solution after referring this article
public List<Entry> GetFinalEntries(int rptId) {
// Get the latest updated time for each linked id
var latestUpdatedTimes = from ent in ctx.Entries
where ent.ReportId == rptId
group ent by ent.LinkedId into svnEnt
select new { LinkedId = svnEnt.Key, UpdatedTime = svnEnt.Max(ent => ent.UpdatedTime) };
// Compare (by joining) to get full entries
var latestEntries = from ent in ctx.Entries
where ent.ReportId == rptId
join time in latestUpdatedTimes
on new { ent.LinkedId, ent.UpdatedTime } equals time
select ent;
return latestEntries.ToList();
}
Now it works fine.
I have linq query as follows:
var result = (from Customer cust in db select new { userNameList = cust.UserName }).ToList();
i want to loop through each value in the list<>
I tried to use the foreach to accomplish this. It is stupid i could not figure it out
I'm using something like this
foreach (List<string> item in result)
{
if (item.ToString() == userName)
{
userExistsFlag = 1;
}
}
But the .net compiler is just freaking out:
and giving me these errors
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List'
Cannot convert type 'AnonymousType#1' to 'System.Collections.Generic.List'
Thanks in anticipation
OF ALL THESE IMPLEMENTATIONS WHICH ONE IS MOST EFFICIENT AND CONSUMES LESS RESOURCES.
IT WOULD BE KIND ENOUGH IF SOME ONE CAN CLARIFY THIS FOR ME.
Shorter using Linq:
bool userExistsFlag = result.Any( x=> x.userNameList == userName);
As suggested in the other answers you do not need to project to an anonymous type:
var userNames = (from Customer cust in db select cust.UserName).ToList();
bool userExists = userNames.Contains(userName);
Edit:
The most efficient - if you do not need the set of user names otherwise - is to query the DB directly to check whether the user name exists, so
bool userExists = db.Any( x => x.UserName == userName);
Credit goes to #Chris Shaffer in the comments and #Cybernatet's answer - he was almost there. I would suggest you accept his answer but use Any() ;-)
Try:
var result = (from Customer cust in db select new { userNameList = cust.UserName }).ToList();
userExistsFlag = result.Where(a=> a.userNameList == userName).Count() > 0;
or
userExistsFlag = (
from Customer cust in db
where cust.UserName = userName
select cust
).Count() > 0;
If your query returns a list of names, your FOREACH loop should look like this
foreach( String name in results ){
...
}
Skip using new { userNameList = cust.UserName } which is making it an anonymous instance. You can try
var result = (from Customer cust in db select cust.UserName ).ToList();
if you're just getting the one property and want a list of strings there is no reason to use an anonymous type. code should work like this:
var result = (from Customer cust in db select cust.UserName).ToList();