I'm trying to get all the assets where Class property equals to one of the values in selectedIClassesList;
Something like this:
from x in Assets where selectedIClassesList.Contains(x.Class) select x
Hi all,
I have a silly question. I would like to know if there is performance deference in these two quries:
var cObject = from cust in entities.Customer
where cust.id == cid
select cust;
and
var cObject = entities.Customer.First( c=> c.id == cid);
My query return only one record as I am querying with the primary key. But do they make any difference?
Hi, I have four tables in my database and i want to join that's and return record's and show that into searchController!
My query is this:
public IQueryable PerformSearch(string query)
{
if (!string.IsNullOrEmpty(query))
{
var results = from tbl1 in context.Table1
join tbl2 in context.Table2 on tbl1.Id equals tbl2.Id
join tbl3 in context.Table3 on tbl2.Id equals tbl3.Id
join tbl4 in context.Table4 on tbl3.Id equals tbl4.Id
where tbl1.col2.Contains(query)
orderby tbl1.Count descending
select new
{
col1 = tbl1.Col1,
col1 = tbl1.Col1,
col1 = tbl1.Col1,
.
.
.
};
return results.AsQueryable();
}
else return null;
}
And this method called in SearchController as below:
public class SearchController : System.Web.Mvc.Controller
{
public System.Web.Mvc.ActionResult Search(System.String query)
{
var search = new Search();
ViewData["result"] = search.PerformSearch(query);
return View("Search");
}
}
I don't know how i can rotate around each record (plus vs intellisense feature) returned by PeformSeach method and show that in view! Also is this a good way?
thanks in advance
Hi
I have three level heirarchal data. using the statement below i managed to display two
level data. I need to extend it to one more level.
Current heirachy is Modules--Documents
I need to extend it as Packages--Modules--Documents
var data = (from m in DataContext.SysModules
join d in DataContext.SysDocuments on m.ModuleID equals d.ModuleID into tempDocs
from SysDocument in tempDocs.DefaultIfEmpty()
group SysDocument by m).ToList();
Regards
Tassadaque
I have the following query:
var groupCats =
from g in groups
group g by g.Value into grouped
select new
{
GroupCategory = grouped.Key,
Categories = GetCategories(grouped.Key, child)
};
This works fine. In the anonymous type returned GroupCategory is a string, and Categories are an Enumerable - what is the proper way to declare this instead of using 'var'?
I tried:
IGrouping<string,string> groupCats =
from g in groups
group g by g.Value into grouped
select new
{
GroupCategory = grouped.Key,
Categories = GetCategories(grouped.Key, child)
};
and
IGrouping<string,Enumerable<string>> groupCats =
from g in groups
group g by g.Value into grouped
select new
{
GroupCategory = grouped.Key,
Categories = GetCategories(grouped.Key, child)
};
In both instances I get:
Cannot implicity convert type....An explicit conversion exists (are you missing a cast)
How do I cast this?
I have questions that may or may not have a question_group
if all the questions do not have a question_group and if I use default if empty like this:
question_group defaultQuestion = new question_group {question_group_id = Guid.Empty};
questions.Select(x => x.question_group).DefaultIfEmpty(defaultQuestion).Distinct();
shouldn't I get an IEnumerable<question_group> containing only the default question_group that I defined? I get null.... what am I missing here?
Here I had very similar xml structure, but now I have this:
<Fields>
<Company>My Company</Company>
<Address2>Villa at beach</Address2>
<Email2>[email protected]</Email2>
<Mobile>333-888</Mobile>
<ContactMethod>Facebook</ContactMethod>
</Fields>
And now I need the same output as on the given link:
Company: My Company
Address2: Villa at beach
Email2: [email protected]
What would be the query for it?
Thanks,
Ile
In SQL Server 2005 and earlier, it is not possible to pass a table variable as a parameter to a stored procedure. When multiple rows of data toSQL Server need to send multiple rows of data toSQL Server, developers either had to send one row at a time or come up with other workarounds to meet requirements. While a VB.Net developer recently informed me that there is a SQLBulkCopy object available in .Net to send multiple rows of data toSQL Server at once, the data still can not be passed to a stored proc.Possibly the most anticipated T-SQL feature of SQL Server 2008 is the new Table-Valued Parameters. This is the ability to easily pass a table to a stored procedure from T-SQL code or from an application as a parameter.
I am trying to optimize this query. It is not slow for now but I am expecting a spike to hit this query in the near future. Is there anything else i can do to make this query faster?
var posts = from p in context.post
where p.post_isdeleted == false && p.post_parentid == null
select new
{
p.post_date,
p.post_id,
p.post_titleslug,
p.post_title,
p.post_descriptionrender,
p.userinfo.user_username,
p.userinfo.user_userid,
p.userinfo.user_GravatarHash,
p.userinfo.user_points,
p.category.catid,
p.category.name,
p.post_answercount,
p.post_hasbestanswer,
p.post_hits,
p.post_isanonymous,
p.post_votecount,
FavoriteCount = context.favorites.Where(x => x.post.post_id == p.post_id).Count(),
tags = from tg in context.posttag
where tg.posttag_postid == p.post_id
select new
{
tg.tag.tag_id,
tg.tag.tag_title
}
};
I'm trying to add the orderby expression on the fly. But when the query below is executed I get the following exception:
System.NotSupportedException: Unable
to create a constant value of type
'Closure type'. Only primitive types
('such as Int32, String, and Guid')
are supported in this context.
The strange thing is, I am query exactly those primitive types only.
string sortBy = HttpContext.Current.Request.QueryString["sidx"];
ParameterExpression prm = Expression.Parameter(typeof(buskerPosting), "posting");
Expression orderByProperty = Expression.Property(prm, sortBy);
// get the paged records
IQueryable<PostingListItemDto> query =
(from posting in be.buskerPosting
where posting.buskerAccount.cmsMember.nodeId == m.Id
orderby orderByProperty
//orderby posting.Created
select new PostingListItemDto { Set = posting }).Skip<PostingListItemDto>((page - 1) * pageSize).Take<PostingListItemDto>(pageSize);
Hope somebody can shed some light on this!
My table structure is as follows:
Person 1-M PesonAddress
Person 1-M PesonPhone
Person 1-M PesonEmail
Person 1-M Contract
Contract M-M Program
Contract M-1 Organization
At the end of this query I need a populated object graph where each person has their:
PesonAddress's
PesonPhone's
PesonEmail's
PesonPhone's
Contract's - and this has its respective
Program's
Now I had the following query and I thought that it was working great, but it has a couple of problems:
from people in ctx.People.Include("PersonAddress")
.Include("PersonLandline")
.Include("PersonMobile")
.Include("PersonEmail")
.Include("Contract")
.Include("Contract.Program")
where people.Contract.Any(
contract => (param.OrganizationId == contract.OrganizationId)
&& contract.Program.Any(
contractProgram => (param.ProgramId == contractProgram.ProgramId)))
select people;
The problem is that it filters the person to the criteria but not the Contracts or the Contract's Programs. It brings back all Contracts that each person has not just the ones that have an OrganizationId of x and the same goes for each of those Contract's Programs respectively.
What I want is only the people that have at least one contract with an OrgId of x with and where that contract has a Program with the Id of y... and for the object graph that is returned to have only the contracts that match and programs within that contract that match.
I kinda understand why its not working, but I don't know how to change it so it is working...
This is my attempt thus far:
from people in ctx.People.Include("PersonAddress")
.Include("PersonLandline")
.Include("PersonMobile")
.Include("PersonEmail")
.Include("Contract")
.Include("Contract.Program")
let currentContracts = from contract in people.Contract
where (param.OrganizationId == contract.OrganizationId)
select contract
let currentContractPrograms = from contractProgram in currentContracts
let temp = from x in contractProgram.Program
where (param.ProgramId == contractProgram.ProgramId)
select x
where temp.Any()
select temp
where currentContracts.Any() && currentContractPrograms.Any()
select new Person { PersonId = people.PersonId, FirstName = people.FirstName, ..., ....,
MiddleName = people.MiddleName, Surname = people.Surname, ..., ....,
Gender = people.Gender, DateOfBirth = people.DateOfBirth, ..., ....,
Contract = currentContracts, ... }; //This doesn't work
But this has several problems (where the Person type is an EF object):
I am left to do the mapping by myself, which in this case there is quite a lot to map
When ever I try to map a list to a property (i.e. Scholarship = currentScholarships) it says I can't because IEnumerable is trying to be cast to EntityCollection
Include doesn't work
Hence how do I get this to work. Keeping in mind that I am trying to do this as a compiled query so I think that means anonymous types are out.
Hi,
I have never used datagrids and such, but today I came across a simple problem and decided to "databind" stuff to finish this faster, however I've found that it doesn't work as I was expecting.
I though that by doing something as simple as:
var q = from cust in dc.Customers
where cust.FirstName == someString
select cust;
var list = new BindingList<Customer>(q.ToList());
return list;
Then using that list in a DataGridView1.DataSource was all that I needed, however, no matter how much I google, I can't find a decent example on how to populate (for add/edit/modify) the results of a single table query into a DataGridView1. Most samples talk about ASP.NET which I lack, this is WinForms.
Any ideas?
I've came across other posts and the GetNewBindingList, but that doesn't seem to change much.
What am I missing (must be obvious)?
Thanks in advance.
Martin.
I have a table with the below structure.
ID VALUE
1 3.2
2 NULL
4 NULL
5 NULL
7 NULL
10 1.8
11 NULL
12 3.2
15 4.7
17 NULL
22 NULL
24 NULL
25 NULL
27 NULL
28 7
I would like to get the max count of consecutive null values in the table.
Any help would be greatly appreciated.
THanks
Ashutosh
public class Class1 : List<Class2>
{
}
public class Class2 : List<Class3>
{
}
public class Class3
{
string str;
int i;
}
public class Program
{
Class1 c = new Class1();
//insert values....
List<Class3> all = ??;
}
How can i get a one-dimensional collection in my var "all" ?
please note I can not modify Class1, class2 and class3...
I am trying to construct a navigation menu using a Categories table from my db.
I have a similar layout as below in Categories table.
public List<Category> CategoryData = new List(new Category[] {
new Category{ CategoryId = 1, Name = "Fruit", ParentCategoryId = null},
new Category{ CategoryId = 2, Name = "Vegetables", ParentCategoryId = null},
new Category{ CategoryId = 3, Name = "Apples", ParentCategoryId = 1},
new Category{ CategoryId = 4, Name = "Bananas", ParentCategoryId = 1},
new Category{ CategoryId = 5, Name = "Cucumber", ParentCategoryId = 2},
new Category{ CategoryId = 6, Name = "Onions", ParentCategoryId = 2}
); }
The above should return something like
Fruit (parent)
"===Apples, Bananas (child)
Vegetables (parent)
"===Cucumber, Onions (child)
I need to be able to pass this as some kind of 'grouped' (grouped by parentid) collection to my View.
How to do this?
Here is an interesting issue I noticed when using the Except Operator:
I have list of users from which I want to exclude some users:
The list of users is coming from an XML file:
The code goes like this:
interface IUser
{
int ID { get; set; }
string Name { get; set; }
}
class User: IUser
{
#region IUser Members
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
#endregion
public override string ToString()
{
return ID + ":" +Name;
}
public static IEnumerable<IUser> GetMatchingUsers(IEnumerable<IUser> users)
{
IEnumerable<IUser> localList = new List<User>
{
new User{ ID=4, Name="James"},
new User{ ID=5, Name="Tom"}
}.OfType<IUser>();
var matches = from u in users
join lu in localList
on u.ID equals lu.ID
select u;
return matches;
}
}
class Program
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load("Users.xml");
IEnumerable<IUser> users = doc.Element("Users").Elements("User").Select
(u => new User
{ ID = (int)u.Attribute("id"),
Name = (string)u.Attribute("name")
}
).OfType<IUser>(); //still a query, objects have not been materialized
var matches = User.GetMatchingUsers(users);
var excludes = users.Except(matches); // excludes should contain 6 users but here it contains 8 users
}
}
When I call User.GetMatchingUsers(users) I get 2 matches as expected.
The issue is that when I call users.Except(matches) The matching users are not being excluded at all! I am expecting 6 users ut "excludes" contains all 8 users instead.
Since all I'm doing in GetMatchingUsers(IEnumerable users) is taking the IEnumerable and just returning
the IUsers whose ID's match( 2 IUsers in this case), my understanding is that by default "Except" will use reference equality
for comparing the objects to be excluded. Is this not how "Except" behaves?
What is even more interesting is that if I materialize the objects using .ToList() and then get the matching users, and call "Except",
everything works as expected!
Like so:
IEnumerable users = doc.Element("Users").Elements("User").Select
(u = new User
{ ID = (int)u.Attribute("id"),
Name = (string)u.Attribute("name")
}
).OfType().ToList(); //explicity materializing all objects by calling ToList()
var matches = User.GetMatchingUsers(users);
var excludes = users.Except(matches); // excludes now contains 6 users as expected
I don't see why I should need to materialize objects for calling "Except" given that its defined on IEnumerable?
Any suggesstions / insights would be much appreciated.
Hi,
I have a class
Class MyObject
{
decimal v1;
decimal dv1;
decimal v2;
decimal dv2;
}
and a
List<MyObject> ...
I need to process every element of the list by adding dv1 to v1 and dv2 to v2
Something like (pseudo-syntax):
myList.Transform(o=>o.v1+=o.dv1, o.v2+=o.dv2)
How can I do this (obvious my pseudo-syntax doesn't works)?
Thank you
I have such XML
<root>
<content>
....
</content>
<index>
....
</index>
<keywords>
....
</keywords>
</root>
But I need to select just and nodes.
<content>
....
</content>
<index>
....
</index>
I found out how to select just one node.
XElement Content = new XElement("content", from el in xml.Elements() select el.Element("content").Elements());
How can I get both nodes?
hi, i want to remove repeated record's from results but distinct don't do this for me! why???
var results = (from words in _Xplorium.Words
join wordFiles in _Xplorium.WordFiles on words.WordId equals wordFiles.WordId
join files in _Xplorium.Files on wordFiles.FileId equals files.FileId
join urls in _Xplorium.Urls on files.UrlId equals urls.UrlId
where files.Title.Contains(query) || files.Description.Contains(query)
orderby wordFiles.Count descending
select new SearchResultItem()
{
Title = files.Title,
Url = urls.Address,
Count = wordFiles.Count,
CrawledOn = files.CrawledOn,
Description = files.Description,
Lenght = files.Lenght,
UniqueKey = words.WordId + "-" + files.FileId + "-" + urls.UrlId
}).Distinct();
I have this simple code but it shows error. I dont know where I am going wrong.
I shows error in last line.."DeleteOnSubmit"
linq_testDataContext db = new linq_testDataContext();
var remove = from aremove in db.logins
where aremove.username == userNameString && aremove.Password == pwdString
select aremove;
db.logins.DeleteOnSubmit(remove);
Thanks,
Ani
I have a logins table which records all login and logout activities. I want to look at all login activities of a particular user within 24 hrs. how to do it? something like this:
var records = from record in db.Logins
where record.Users.UserId == userId
&& record.Timestamp <= (DateTime.Now + 24)
select record;
record.Timestamp <= (DateTime.Now + 24) is wrong here. I am using C# 3 + L2E.
I use c# 4 asp.net and EF 4. I'm precompiling a query, the result should be a collection of Anonymous Type.
At the moment I use this code.
public static readonly Func<CmsConnectionStringEntityDataModel, string, dynamic>
queryContentsList =
CompiledQuery.Compile<CmsConnectionStringEntityDataModel, string, dynamic>
(
(ctx, TypeContent) => ctx.CmsContents.Where(c => c.TypeContent == TypeContent
& c.IsPublished == true & c.IsDeleted == false)
.Select(cnt => new
{
cnt.Title,
cnt.TitleUrl,
cnt.ContentId,
cnt.TypeContent, cnt.Summary
}
)
.OrderByDescending(c => c.ContentId));
I suspect the RETURN for the FUNCTION Dynamic does not work properly and I get this error
Sequence contains more than one element enter code here.
I suppose I need to return for my function a Collection of Anonymous Types...
Do you have any idea how to do it? What I'm doing wrong? Please post a sample of code thanks!
Update:
public class ConcTypeContents
{
public string Title { get; set; }
public string TitleUrl { get; set; }
public int ContentId { get; set; }
public string TypeContent { get; set; }
public string Summary { get; set; }
}
public static readonly Func<CmsConnectionStringEntityDataModel, string, ConcTypeContents> queryContentsList =
CompiledQuery.Compile<CmsConnectionStringEntityDataModel, string, ConcTypeContents>(
(ctx, TypeContent) => ctx.CmsContents.Where(c => c.TypeContent == TypeContent & c.IsPublished == true & c.IsDeleted == false)
.Select(cnt => new ConcTypeContents { cnt.Title, cnt.TitleUrl, cnt.ContentId, cnt.TypeContent, cnt.Summary }).OrderByDescending(c => c.ContentId));
I have a business layer that has DTOs that are used in the presentation layer. This application uses entity framework.
Here is an example of a class called RoleDTO:
public class RoleDTO
{
public Guid RoleId { get; set; }
public string RoleName { get; set; }
public string RoleDescription { get; set; }
public int? OrganizationId { get; set; }
}
In the BLL I want to have a method that returns a list of DTO. I would like to know which is the better approach: returning IQueryable or list of DTOs. Although I feel that returning IQueryable is not a good idea because the connection needs to be open. Here are the 2 different methods using the different approaches:
First approach
public class RoleBLL
{
private servicedeskEntities sde;
public RoleBLL()
{
sde = new servicedeskEntities();
}
public IQueryable<RoleDTO> GetAllRoles()
{
IQueryable<RoleDTO> role = from r in sde.Roles
select new RoleDTO()
{
RoleId = r.RoleID,
RoleName = r.RoleName,
RoleDescription = r.RoleDescription,
OrganizationId = r.OrganizationId
};
return role;
}
Note: in the above method the DataContext is a private attribute and set in the constructor, so that the connection stays opened.
Second approach
public static List<RoleDTO> GetAllRoles()
{
List<RoleDTO> roleDTO = new List<RoleDTO>();
using (servicedeskEntities sde = new servicedeskEntities())
{
var roles = from pri in sde.Roles
select new { pri.RoleID, pri.RoleName, pri.RoleDescription };
//Add the role entites to the DTO list and return. This is necessary as anonymous types can be returned acrosss methods
foreach (var item in roles)
{
RoleDTO roleItem = new RoleDTO();
roleItem.RoleId = item.RoleID;
roleItem.RoleDescription = item.RoleDescription;
roleItem.RoleName = item.RoleName;
roleDTO.Add(roleItem);
}
return roleDTO;
}
}
Please let me know, if there is a better approach.