Multiple LINQ to XML query - linq

I am trying to figure out a multiple where clause that is derived from two different elements. Basically, I want to be able to filter based on name attributes of DataType & Service elements. Appreciate any feedback. Thanks Jay
var services = from dt in doc.Descendants("DataType")
where (string)dt.Attribute("name") == "WELL_INDUSTRY" && (string)dt.Elements("Service").Attributes == "Well_Industry"
from service in dt.Elements("Services").Elements("Service").Elements("Layers").Elements("Layer")
select new
{
Name = (string)service.Attribute("name"),
};
XML:
<DataTypes>
<DataType name="WELL_INDUSTRY">
<Spatial>
<Services>
<Service name="Well_Industry" group="Well" status="Primary" >
<Layers>
<layer name="Bottom Hole Wells" ></layer>
<layer name="Bottom Hole Wells2" ></layer>
</Layers>

I think you're looking for something like that:
var services = from dt in doc.Descendants("DataType")
where (string)dt.Attribute("name") == "WELL_INDUSTRY"
from service in dt.Element("Spatial")
.Elements("Services")
.Elements("Service")
where (string)service.Attribute("name") == "Well_Industry"
from layer in service.Element("Layers")
.Elements("Layer")
select new
{
ServiceName = (string)service.Attribute("name"),
Layers = layer.Select(x => (string)x).ToList()
};
You can add another where after from service ....
You are still able to use service variable within select part of the query.
However, querying for ServiceName when there is ServiceName == "myName" check before seems to be useless. In case you need names of layers, use following select:
select new
{
Name = (string)layes.Attribute("name")
};

var services = from dt in doc.Descendants("DataType")
where (string)dt.Attribute("name") == "WELL_INDUSTRY"
from s in dt.Descendants("Service")
where (string)s.Attribute("name") == "Well_Industry"
from l in s.Descendants("Layer")
select new {
Name = (string)l.Attribute("name")
};
Same can be achieved with XPath:
var xpath = "//DataType[#name='WELL_INDUSTRY']//Service[#name='Well_Industry']//layer";
var services = from l in doc.XPathSelectElements(xpath)
select new {
Name = (string)l.Attribute("name")
};

Related

How to write this LINQ with foreach in a better way

I was doing project in MVC3 with Entity framework. I have a LINQ query with foreach. Everything is fine. But when the data size goes up, i was facing performance issues. I dont have much experience with LINQ. So I couldn't fix my issue. Pls have a look at my code and provide a better suggestion for me.
Code
List<int> RouteIds = db.Cap.Where(asd => asd.Type == 3).Select(asd => asd.UserId).ToList();
var UsersWithRoutingId = (from route in db.RoutingListMembers
where RouteIds.Contains(route.RoutingListId.Value) && route.User.UserDeptId == Id
select
new RoutingWithUser
{
UserId = route.UserId,
RoutingId = route.RoutingListId
});
var ListRouteValue = (from cap in db.CareAllocationPercents
where cap.Type == 3
select new UserWithDeptId
{
Year = (from amt in db.CareAllocations where amt.CareItemId == cap.CareItemId select amt.Year).FirstOrDefault(),
UserId = cap.UserId,
UserDeptId = (from userdept in db.Users where userdept.Id == cap.UserId select userdept.UserDeptId).FirstOrDefault(),
});
List<UserWithDeptId> NewRouteList = new List<UserWithDeptId>();
ListRouteValue = ListRouteValue.Where(asd => asd.Year == Year);
foreach (var listdept in ListRouteValue)
{
foreach (var users in UsersWithRoutingId)
{
if (users.RoutingId == listdept.UserId)
{
UserWithDeptId UserwithRouteObj = new UserWithDeptId();
UserwithRouteObj.UserId = users.UserId;
UserwithRouteObj.Year = listdept.Year;
UserwithRouteObj.UserDeptId = db.Users.Where(asd => asd.Id == users.UserId).Select(asd => asd.UserDeptId).FirstOrDefault();
NewRouteList.Add(UserwithRouteObj);
}
}
}
NewRouteList = NewRouteList.Where(asd => asd.UserDeptId == Id).ToList();
Thanks,
You have to use join in first statement. Examples of how to do this are for example here: Joins in LINQ to SQL
I have some idea for you:
First:
Take care to complete your where close into your linq query to get just what you need to.
With Linq on collection, you can remove one foreach loop. I don't know the finality but, i've tryied to write something for you:
var UsersWithRoutingId = (from route in db.RoutingListMembers
where RouteIds.Contains(route.RoutingListId.Value) && route.User.UserDeptId == Id
select
new RoutingWithUser
{
UserId = route.UserId,
RoutingId = route.RoutingListId
});
var ListRouteValue = (from cap in db.CareAllocationPercents
where cap.Type == 3
select new UserWithDeptId
{
Year = (from amt in db.CareAllocations
where amt.CareItemId == cap.CareItemId && amt.Year == Year
select amt.Year).FirstOrDefault(),
UserId = cap.UserId,
UserDeptId = (from userdept in db.Users
where userdept.Id == cap.UserId && userdept.UserDeptId == Id
select userdept.UserDeptId).FirstOrDefault(),
});
List<UserWithDeptId> NewRouteList = new List<UserWithDeptId>();
foreach (var listdept in ListRouteValue)
{
var user = UsersWithRoutingId.Where(uwri => uwri.RoutingId == listdept.UserId).FirstOrDefault();
if (user != null)
{
NewRouteList.Add(new UserWithDeptId { UserId=user.UserId, Year=listdept.Year, UserDeptId=listdept.UserDeptId });
}
}
return NewRouteList
Is that right for you ?
(i don't poll the db.user table do get the UserDeptId for the NewRouteList assuming that the one in the listdept is the good one)
Second:
Take care of entity data loading, if you have tables with foreign key, take care to remove the lazy loading if you don't need the children of your table to be loaded at same time. Imagine the gain for multiple table with foreign key pointing to others.
Edit:
Here is a link that explain it:
http://msdn.microsoft.com/en-us/library/vstudio/dd456846%28v=vs.100%29.aspx

Alternative coding to a conditional var inferred-type query LINQ to XML?

This is a follow up on a related topic found here
https://stackoverflow.com/questions/1987485/conditionally-assign-c-var-as-elegant-as-it-gets
if I am doing the following:
var query = (SearchString == "" ?
(
from MEDIA in xdoc.Descendants("MEDIA")
select new
{
PLAY = MEDIA.Element("PLAY").Value,
PIC = MEDIA.Element("PIC").Value,
TTL = MEDIA.Element("TTL").Value
}
):
from MEDIA in xdoc.Descendants("MEDIA")
where MEDIA.Element("TTL").ToString().ToLower().Contains(SearchString)
select new
{
PLAY = MEDIA.Element("PLAY").Value,
PIC = MEDIA.Element("PIC").Value,
TTL = MEDIA.Element("TTL").Value
}
) ;
How would I declare the query type to make it static at the class level?
Alternatively, in the referenced post Marc Gravell point out a different approach
IQueryable<Part> query = db.Participant;
if(email != null) query = query.Where(p => p.EmailAddress == email);
if(seqNr != null) query = query.Where(p => p.SequenceNumber == seqNr);
...
How would I declare/recode the query in my case?
Here is my wild attempts :)
IEnumerable<XElement> query = xdoc.Descendants("MEDIA");
if (SearchString != "" )
query = query.Where(m => m.Element("TTL").ToString().ToLower().Contains(SearchString));
Thank you.
How would I declare the query type to make it static at the class level?
You can't. Anonymous types are, well, anonymous... so they don't have a name you can use to declare variables. Your query is of type IEnumerable<something>, but you can't refer to something in your code. So you need to create a specific class that represent the results of your query, and use it instead of the anonymous type.

Only primitive types ('such as Int32, String, and Guid') are supported in this context when I try updating my viewmodel

I am having some trouble with a linq query I am trying to write.
I am trying to use the repository pattern without to much luck. Basically I have a list of transactions and a 2nd list which contains the description field that maps against a field in my case StoreItemID
public static IList<TransactionViewModel> All()
{
var result = (IList<TransactionViewModel>)HttpContext.Current.Session["Transactions"];
if (result == null)
{
var rewardTypes = BusinessItemRepository.GetItemTypes(StoreID);
HttpContext.Current.Session["Transactions"] =
result =
(from item in new MyEntities().TransactionEntries
select new TransactionViewModel()
{
ItemDescription = itemTypes.FirstOrDefault(r=>r.StoreItemID==item.StoreItemID).ItemDescription,
TransactionDate = item.PurchaseDate.Value,
TransactionAmount = item.TransactionAmount.Value,
}).ToList();
}
return result;
}
public static List<BusinessItemViewModel>GetItemTypes(int storeID)
{
var result = (List<BusinessItemViewModel>)HttpContext.Current.Session["ItemTypes"];
if (result == null)
{
HttpContext.Current.Session["ItemTypes"] = result =
(from items in new MyEntities().StoreItems
where items.IsDeleted == false && items.StoreID == storeID
select new BusinessItemViewModel()
{
ItemDescription = items.Description,
StoreID = items.StoreID,
StoreItemID = items.StoreItemID
}).ToList();
}
return result;
However I get this error
Unable to create a constant value of type 'MyMVC.ViewModels.BusinessItemViewModel'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
I know its this line of code as if I comment it out it works ok
ItemDescription = itemTypes.FirstOrDefault(r=>r.StoreItemID==item.StoreItemID).ItemDescription,
How can I map ItemDescription against my list of itemTypes?
Any help would be great :)
This line has a problem:
ItemDescription = itemTypes.FirstOrDefault(r=>r.StoreItemID==item.StoreItemID)
.ItemDescription,
Since you are using FirstOrDefault you will get null as default value for a reference type if there is no item that satifies the condition, then you'd get an exception when trying to access ItemDescription - either use First() if there always will be at least one match or check and define a default property value for ItemDescription to use if there is none:
ItemDescription = itemTypes.Any(r=>r.StoreItemID==item.StoreItemID)
? itemTypes.First(r=>r.StoreItemID==item.StoreItemID)
.ItemDescription
: "My Default",
If itemTypes is IEnumerable then it can't be used in your query (which is what the error message is telling you), because the query provider doesn't know what to do with it. So assuming the that itemTypes is based on a table in the same db as TransactionEntities, then you can use a join to achieve the same goal:
using (var entities = new MyEntities())
{
HttpContext.Current.Session["Transactions"] = result =
(from item in new entities.TransactionEntries
join itemType in entities.ItemTypes on item.StoreItemID equals itemType.StoreItemID
select new TransactionViewModel()
{
ItemDescription = itemType.ItemDescription,
TransactionDate = item.PurchaseDate.Value,
TransactionAmount = item.TransactionAmount.Value,
CustomerName = rewards.CardID//TODO: Get customer name
}).ToList();
}
I don't know the structure of your database, but hopefully you get the idea.
I had this error due a nullable integer in my LINQ query.
Adding a check within my query it solved my problem.
query with problem:
var x = entities.MyObjects.FirstOrDefault(s => s.Obj_Id.Equals(y.OBJ_ID));
query with problem solved:
var x = entities.MyObjects.FirstOrDefault(s => s.Obj_Id.HasValue && s.Obj_Id.Value.Equals(y.OBJ_ID));

Using LINQ to pull MembershipUser.Username into a new object

I have the following code and I need to pull out each user's username from the membership tables:
var results = (from u in db.U_USER
where u.Forename.ToLower().Contains(search)
|| u.Surname.ToLower().Contains(search)
select new ExUser
{
MembershipId = u.MembershipId,
Surname = u.Surname,
Forename = u.Forename,
Username = Membership.GetUser(u.MembershipId).UserName
});
Now I know why im getting the following, but can anybody recommend a solution?
LINQ to Entities does not recognize the method 'System.Web.Security.MembershipUser GetUser
LINQ to Entities is trying to translate your select expression into T-SQL, which it can't because there's no ExUser etc. in T-SQL.
Finhish off the expression with a call to AsEnumerable or similar, and then perform the projection:
var results = (from u in db.U_USER
where u.Forename.ToLower().Contains(search)
|| u.Surname.ToLower().Contains(search)
select u)
.AsEnumerable()
.Select(u => new ExUser
{
MembershipId = u.MembershipId,
Surname = u.Surname,
Forename = u.Forename,
Username = Membership.GetUser(u.MembershipId).UserName
});
You can do it by forcing the results into memory by using AsEnumerable. When the results are in memory you can call Membership.GetUser without linq attempting to translate it to sql:
var results = (from u in db.U_USER
where u.Forename.ToLower().Contains(search) || u.Surname.ToLower().Contains(search)
).AsEnumerable().Select(u => new ExUser {
MembershipId = u.MembershipId,
Surname = u.Surname,
Forename = u.Forename,
Username = Membership.GetUser(u.MembershipId).UserName
});

How to do a nested count with OData and LINQ?

Here is the query I am trying to run from my OData source:
var query = from j in _auditService.AuditJobs.IncludeTotalCount()
orderby j.Description
select new
{
JobId = j.ID,
Description = j.Description,
SubscriberCount = j.JobRuns.Count()
};
It runs great if I don't use the j.JobRuns.Count(), but if I include it I get the following error:
Constructing or initializing instances
of the type
<>f__AnonymousType1`3[System.Int32,System.String,System.Int32]
with the expression j.JobRuns.Count()
is not supported.
It seems to be a problem of attempting to get the nested count through OData. What is a work around for this? I was trying to avoid getting the whole nested collection for each object just to get a count.
Thanks!
As of today the OData protocol doesn't support aggregates.
Projections yes, but projections that include aggregate properties no.
Alex
You need .Net 4.0 and In LinqPad you can run following over netflix OData Service
void Main()
{
ShowPeopleWithAwards();
ShowTitles();
}
// Define other methods and classes here
public void ShowPeopleWithAwards()
{
var people = from p in People.Expand("Awards").AsEnumerable()
where p.Awards.Count > 0
orderby p.Name
select new
{
p.Id,
p.Name,
AwardCount = p.Awards.Count,
TotalAwards = p.Awards.OrderBy (a => a.Type).Select (b => new { b.Type, b.Year} )
};
people.Dump();
}
public void ShowTitles()
{
var titles = from t in Titles.Expand("Awards").AsEnumerable()
where t.ShortName != string.Empty &&
t.ShortSynopsis != string.Empty &&
t.Awards.Count > 0
select t;
titles.Dump();
}
You can now use my product AdaptiveLINQ and the extension method QueryByCube.

Resources