I have a LINQ2SQL Query:
//Pulling the Product_ID from the PlanMaster Table from WebEnroll DB!
var tr = from s in dt.PlanMasters
where s.PlanName == productName
select new
{
s.Product_ID
};
This is pulling Product_ID which is working good. Now I want to ADD a record into another LINQ statement which is here:
CommissionsV2DataContext cv = new CommissionsV2DataContext();
Entity_Product_Point ev = new Entity_Product_Point();
ev.Entity_ID = getEntity;
ev.Product_ID = tr.; ?????
I want to store the variable which I am getting from tr (that is Product_ID) to ev.Product_ID.
How should I convert an object to an INT? Thank you!
The problem is that your first query returns a collection of objects with an integer property, not a single integer. You can change your query to this instead:
var tr = (
from s in dt.PlanMasters
where s.PlanName == productName
select s.Product_ID).First();
Or, more cleanly, IMO:
var tr = dt.PlanMasters.First(s => s.PlanName == productName).Product_ID;
tr is a collection. You have to call tr.FirstOrDefault().Product_ID.
I would change your linq query to select just the s.Product_ID instead of select newing a new anonymous object containing the ID.
var tr = from s in dt.PlanMasters
where s.PlanName == productName
select s.Product_ID;
Your second code block could then be simply ev.Product_ID = tr.First();
CommissionsV2DataContext cv = new CommissionsV2DataContext();
Entity_Product_Point ev = new Entity_Product_Point();
ev.Entity_ID = getEntity;
ev.Product_ID = tr.First();
ev.Product_ID = tr.First().Product_ID;
Related
I want to get all items in the database using LINQ where the Title starts with special characters or number, I already tried the code below but it's not working.
Thanks
result = (from asset in _db.Query<Asset>()
where !char.IsLetter(asset.Title[0])
select new AssociatedItem { Id = asset.AssetId, Title = asset.Title, Type = Constants.FeedbackTypes.ASSET }).ToList();
That's because char.IsLetter is not a dbFunction.
You can apply where after converting the results ToList()
result = (from asset in _db.Query<Asset>()
select new AssociatedItem { Id = asset.AssetId, Title = asset.Title, Type = Constants.FeedbackTypes.ASSET }).ToList()
.Where(a => !char.IsLetter(a.Title[0])).ToList();
PS: Try to identify some other where clause for the db query to limit the results.
I'd give the SqlMethods class from the System.Data.Linq.SqlClient namespace a shot.
result = (from asset in _db.Query<Asset>()
where !SqlMethods.Like(asset.Title, "[a-Z]%")
select
new AssociatedItem
{
Id = asset.AssetId,
Title = asset.Title,
Type = Constants.FeedbackTypes.ASSET
}).ToList();
I just need to make full outer join with Linq, But When i union two quires i get this error:
Instance argument: cannot convert from 'System.Linq.IQueryable' to 'System.Linq.ParallelQuery
And here is my full Code:
using (GoodDataBaseEntities con = new GoodDataBaseEntities())
{
var LeftOuterJoin = from MyCustomer in con.Customer
join MyAddress in con.Address
on MyCustomer.CustomerId equals MyAddress.CustomerID into gr
from g in gr.DefaultIfEmpty()
select new { MyCustomer.CustomerId, MyCustomer.Name, g.Address1 };
var RightOuterJoin = from MyAddress in con.Address
join MyCustomer in con.Customer
on MyAddress.CustomerID equals MyCustomer.CustomerId into gr
from g in gr.DefaultIfEmpty()
select new { MyAddress.Address1, g.Name };
var FullOuterJoin = LeftOuterJoin.Union(RightOuterJoin);
IEnumerable myList = FullOuterJoin.ToList();
GridView1.DataSource = myList;
GridView1.DataBind();
}
The types of your two sequences are not the same, so you can't do a Union.
new { MyCustomer.CustomerId, MyCustomer.Name, g.Address1 };
new { MyAddress.Address1, g.Name };
Try making sure that the fields have the same names and types in the same order.
Why not select it all as one thing? Depending on your setup (i.e., if you have foreign keys properly set up on your tables), you shouldn't need to do explicit joins:
var fullJoin = from MyCustomer in con.Customer
select new {
MyCustomer.CustomerId,
MyCustomer.Name,
MyCustomer.Address.Address1,
MyCustomer.Address.Name
};
Method syntax:
var fullJoin = con.Customers.Select(x => new
{
x.CustomerId,
x.Name,
x.Address.Address1,
x.Address.Name
});
union appends items from one collection to the end of another collection, so if each collection had 5 items, the new collection will have 10 items.
What you seem to want is to end up with 5 rows with more infomration is each. That's not a job for Union. You might be able to do it with Zip(), but you'll really be best with the single query as shown by DLeh.
I am using LINQ to SQL in my C# tutorial project but I have basic knowledge of it.
I made a SQL query like this:
SELECT ID,HeroName,HeroRarity,Initiative,Attack,Attack1
FROM CharactersName
WHERE ID IN(
SELECT HeroID
FROM Hero_Group
WHERE GroupID=1
)
(Hero_Group) is a table to deal with a many-to-many relation between (CharactersName) table and another table named (Groups) where a character can be in more than one group.
I tried to write it in LINQ like this:
void FilterGroup()
{
HDAEntities db = new HDAEntities();
var query = from obj in db.CharactersNames
where obj.ID == from obj2 in db.Hero_Group
where obj2.GroupID == comboBox1.SelectedIndex
select new
{
obj2.GroupID
}
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
}
But of course this is gibberish.
Can someone help me, please ? (be informed that I have little knowledge of LINQ to SQL)
~TIA~
You can do it like this:
void FilterGroup()
{
HDAEntities db = new HDAEntities();
var subQuery = db.Hero_Group.Where(h => h.GroupID == comboBox1.selectedIndex)
.Select(h => h.GroupID);
var query = from obj in db.CharactersNames
where subQuery.Contains(obj.ID)
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
var result = query.ToList(); // this is where your query and subquery are evaluated and sent to the database
db.Dispose();
db = null;
}
Note that the subQuery is not evaluated until you call ToList(). You also need to dispose the object (or try the using statement to create the HDAEntities object). Also, make sure you don't dispose the db before evaluating the query (calling ToList after Dispose will throw an exception).
var query = from obj in db.CharactersNames
where (from obj2 in db.Hero_Group
where obj2.GroupID == comboBox1.SelectedIndex
select new {obj2.GroupID}).Contains(obj.ID)
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
var query = from obj in db.CharactersNames
where (from obj2 in db.Hero_Group
where obj2.GroupID == comboBox1.SelectedIndex
select new {obj2.GroupID}).Contains(obj.ID)
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
I have a database table that contains an nvarchar column like this:
1|12.6|18|19
I have a Business Object that has a Decimal[] property.
My LINQ Query looks like this:
var temp = from r in db.SomeTable select new BusinessObject {
// Other BusinessObject Properties snipped as they are straight 1:1
MeterValues = r.MeterValues.Split('|').Select(Decimal.Parse).ToArray()
};
var result = temp.ToArray();
This throws an NotSupportedException: Method 'System.String[] Split(Char[])' has no supported translation to SQL.
That kinda sucks :) Is there any way I can do this without having to add a string property to the business object or selecting an anonymous type and then iterating through it?
My current "solution" is:
var temp = from r in db.SomeTable select new {
mv = r.MeterValues,
bo = new BusinessObject { // all the other fields }
};
var result = new List<BusinessObject>();
foreach(var t in temp) {
var bo = t.bo;
bo.MeterValues = t.mv.Split('|').Select(Decimal.Parse).ToArray();
result.Add(bo);
}
return result.ToArray(); // The Method returns BusinessObject[]
That's kinda ugly though, with that temporary list.
I've tried adding a let mv = r.MeterValues.Split('|').Select(Decimal.Parse).ToArray() but that essentially leads to the same NotSupportedException.
This is .net 3.5SP1 if that matters.
You need to force the select clause to run on the client by calling .AsEnumerable() first:
var result = db.SomeTable.AsEnumerable().Select(r => new BusinessObject {
...
MeterValues = r.MeterValues.Split('|').Select(Decimal.Parse).ToArray()
}).ToList();
You can't use split, but in this scenario you can do the following:
// Database value is 1|12.6|18|19
string valueToFind = "19";
var temp = from r in db.SomeTable.Where(r => ("|" + r.MeterValues + "|").Contains("|" + valueToFind + "|"));
This code adds outer pipes (|) to the database value on the fly inside the query so you can do start, middle, and end value matches on the string.
For example, the above code looks for "|19|" inside "|1|12.6|18|19|", which is found and valid. This will work for any other valueToFind.
You don't need to use a temporary list:
var query = from r in db.SomeTable
select new
{
r.Id,
r.Name,
r.MeterValues,
...
};
var temp = from x in query.AsEnumerable()
select new BusinessObject
{
Id = x.Id,
Name = x.Name,
MeterValues = x.mv.Split('|').Select(Decimal.Parse).ToArray(),
...
};
return temp.ToArray();
Unfortunately its the IQueryable you are using (Linq to SQL) that is not supporting the Split function.
You are really only left with the IEnumerable (Linq to Objects) support for it in this case. You second code snippet is what you need to do, or something like...
var temp = (from r in db.SomeTable select new {
mv = r.MeterValues,
bo = new BusinessObject { // all the other fields }
}).AsEnumerable().Select(blah, blah) ;
I have this LINQ query:
var returnList = from TblItemEntity item in itemList
join TblClientEntity client in clientList
on item.ClientNo equals client.ClientNumber
join TblJobEntity job in jobList
on item.JobNo equals job.JobNo
where item.ClientNo == txtSearchBox.Text //Is this filter wrong?
orderby client.CompanyName
select new { FileId = item.FileId, CompanyName = client.CompanyName, LoanStatus = item.LoanStatus, JobNo = job.JobNo, JobFinancialYE = job.JobFinancialYE, VolumeNo = item.VolumeNo };
Why doesn't this return anything?
P/S : All of them are of string datatype.
Have you tried to remove parts of the join to figure out where the problem is and then add those removed parts back again one after one? Start with:
var returnList = from TblItemEntity item in itemList
where item.ClientNo == txtSearchBox.Text //Is this filter wrong?
select new { FileId = item.FileId };
Since you're doing inner joins there could be that one of the joins filters out all the items.
EDIT: When debugging don't expand the return type, the select new {FileId = item.FileId} is all you need to debug.
Still waiting on that sample data.
You say you're getting results filtering by other attributes so why should this be any different? Assuming the user-input txtSearchBox has a reasonable value, try printing the values out onto the debug console and see if you're getting reasonable results. Look at the output window. Try this version of your query:
Func<string,bool> equalsSearch = s =>
{
var res = s == txtSearchBox.Text;
Debug.WriteLine("\"{0}\" == \"{1}\" ({2})", s, txtSearchBox.Text, res);
return res;
};
var returnList = from TblItemEntity item in itemList
join TblClientEntity client in clientList
on item.ClientNo equals client.ClientNumber
join TblJobEntity job in jobList
on item.JobNo equals job.JobNo
//where item.ClientNo == txtSearchBox.Text //Is this filter wrong?
where equalsSearch(item.ClientNo) //use our debug filter
orderby client.CompanyName
select new { FileId = item.FileId, CompanyName = client.CompanyName, LoanStatus = item.LoanStatus, JobNo = job.JobNo, JobFinancialYE = job.JobFinancialYE, VolumeNo = item.VolumeNo };
Why doesn't this return anything?
There two possibilites:
1) The join is empty, that is, no items, clients and jobs have matching ID's.
2) The where clause is false for all records in the join.
To troubleshoot this you will have to remove the where clause and/or some of the joined tables to see what it takes to get any results.