converting from linq var result to another object - linq

using the following LINQ query I want 'chosen' to be a 'User' object which I know and can manipulate, but it's not. How can I convert it to 'User'?
Thanks
Console.Write("User name:");
String nickname = Console.ReadLine();
var loggedin = from user in userList
where user.getNickname().Equals(nickname)
select user;

Currently, your query returns an IEnumerable<T> where T is the type of elements in userList.
It seems like you're after the FirstOrDefault eager operation to retrieve only a single User object if present.
var loggedin = (from user in userList
where user.getNickname().Equals(nickname)
select user).FirstOrDefault();
loggedin will be null if userList is empty, or if there is no element satisfying the provided predicate.
Using method syntax the same can be accomplished like this:
var loggedin = userList.FirstOrDefault(user => user.getNickname().Equals(nickname));

Related

can not addRange of items to var using linq and c#

I have a following list of users:
var roles = userRoleRepository.Get(q => q.user_id.Equals(username, StringComparison.InvariantCultureIgnoreCase));
roles has two properties one is (ID,Name) ,how can i add a collection to this after i get the list?since roles,does not have add or addrange,i want to add("124","Jack")
It seems to me that UserRoleRepository is an object of one of your (company's) own classes. This class has a Get function that has some return value.
Alas you forgot to tell us the returned type. From the code snippet, I assume that the returned object is not a sequence of objects, but one single object, probably something that you'd call a UserRole. The returned UserRole is the one in the userRoleRepository that has a user_id that equals some string userName.
As the Get function returns only one UserRole it is not a meaningful action to add a collection to this one object, unless this UserRole has a function to add a collection. But as you told us: your UserRole does not have such a function.
Or are you a bit sloppy in your description and do you want to add some UserRoles to the collection of UserRoles that would be the return of your Get function? Alas again: you didn't give us a definition of the return value of your Get function.
If Get returns one UserRole and you want the combination of this fetched UserRole together with your own sequence of UserRoles, do the following:
UserRole fetchedUserRole = userRoleRepository.Get(...);
List<UserRole> userRoles = new List<UserRole>();
userRoles.Add(fetchedUserRole);
return userRoles.Concat(myOwnUserRoleCollection);
If on the other hand Get returns a sequence of USerRole, the code would be even simpler:
IEnumerable<UserRole> fetchedUserRoles = userRoleRepository.Get(...);
return fetchedUserRoles.Concat(myOwnUserRoleCollection);

Displaying records from database which are equal to logged on user

I have created an MVC3 application which needs to show user specific data. The problem I am having is trying to display records which are equal to #user.Identity.Name.
The following Linq to SQL has been used to try to accomplish this:
public ActionResult Index()
{
using (var db = new mydatEntities())
{
var details = from t in db.testadtas
where t.UserID == Viewbag.UsersRecord
select t;
return View();
}
}
(Update)
New to c# and Linq and finding it hard to write a query which will only display the logged on users records.
I have used the code below
MembershipUser currentUser = Membership.GetUser (User.Identity.Name, true /* userIsOnline */);
Viewbag.UsersRecord = currentUser.ProviderUserKey;
I have then input the Viewbag.UserRecord into a textbox which updates a database field with the UserID in a table I have created.
I now want to write a linq query to say if UserID = Viewbag.UserRecord then show record with the UserID only
Is this a correct method to use for showing logged on user records?
or is there any other way which I can implement this in MVC3?
Just use HttpContext.User.Identity.Name

Can I filter the Users returned by GetAllUsers based on a role they are in

I am trying to create an administration interface where users and roles (among other things) can be administered. I have a list of users who can be edited, deleted or viewed. I have this code in the action:
var model = Membership.GetAllUsers()
.Cast<MembershipUser>()
.Select(x => new UserModel
{
UserName = x.UserName,
Email = x.Email,
UserRoles = Roles.GetRolesForUser(x.UserName)
});
return View(model);
This is all fine except that I don't want admins to be able to edit each other. So I need to filter out all users in the "super admin" role. I can certainly figure this out by stepping through each role for each user to see if they are a member. I am wondering if there is a nice sucinct way to do this by filtering the result set in the Select statement, or using Except or Where
I would normally think about the sql I want generated then try write the linq, filtering by roles should be fairly easy with a simple where statement.
However it appears you're trying to abstract each part of the query into smaller bits, this may make it easier to write but can have a devastating effect on performance. For example, I wouldn't be suprised if the GetRolesForUser method you are calling causing an extra database query per user that is returned by GetAllUsers, using the Include method is a much nicer way to get all roles at the same time.
var model = context.Users
.Include(user => user.UserRoles)
.Where(user => !user.UserRoles.Any(role => role == superAdmin)
.Select(user => new UserModel() { UserName = user.UserName, Email = user.Email, UserRoles = user.UserRoles});

Linq Order By not working

The Linq query "order by" is not working and I've followed all the suggestions found on your site and other sites. Any assistance would be appreciated.
[WebGet]
public IQueryable<vw_providercharge_providers> GetChargeProviders(int submitted)
{
var results = (from p in this.CurrentDataSource.vw_providercharge_providers
where p.submitted == submitted
orderby p.fullname
select p);
return results;
}
Thanks for your input!
Yes, this is a WebGet method for a WCF data service. I get a 400 error if I don't return an IQueryable type, so I modified your suggestion a little. Unfortunately, it still seems to disregard any order-by.
[WebGet]
public IQueryable<vw_providercharge_providers> GetChargeProviders(int submitted)
{
var results = (from p in this.CurrentDataSource.vw_providercharge_providers
where p.submitted == submitted
orderby p.fullname
select p).ToArray();
results.OrderBy(p => p.patientname);
return results;
}
I notice you return an IQueryable<T> - are you calling any LINQ methods on the result before you enumerate it?
Not all LINQ methods preserve order. Most commonly, calling Distinct() after you do the ordering will destroy the order.
Since your method is a marked with a WebGet attribute, I'm assuming that you are calling this method from a Web endpoint, therefore you may need to collapse the collection prior to send it through internet.
Try:
[WebGet]
public vw_providercharge_providers[] GetChargeProviders(int submitted)
{
var results = (from p in this.CurrentDataSource.vw_providercharge_providers
where p.submitted == submitted
orderby p.fullname
select p).ToArray();
return results;
}
This way you have the guarantee that the GetChargeProviders method returns and array instead of an linq expression.
Regards,
I found the cause of the issue.
I had not set the "fullname" column as an Entity Key for the "vw_providercharge_providers" data model entity. Only the identity column was set as an Entity Key. I didn't realize that was a requirement to use it in an order by clause.
Thanks again for your input.

How do you re-use select statements with Entity Framework?

Given the following query:
var query = from item in context.Users // Users if of type TblUser
select new User() // User is the domain class model
{
ID = item.Username,
Username = item.Username
};
How can I re-use the select part of the statement in other queries? I.e.
var query = from item in context.Jobs // Jobs if of type TblJob
select new Job() // Job is the domain class model
{
ID = item.JobId,
User = ReuseAboveSelectStatement(item.User);
};
I tried just using a mapper method:
public User MapUser(TblUser item)
{
return item == null ? null : new User()
{
ID = item.UserId,
Username = item.Username
};
}
With:
var query = from item in context.Users // Users if of type TblUser
select MapUser(item);
But if I do this, then the framework throws an error such as:
LINQ to Entities does not recognize
the method 'MapUser(TblUser)' method,
and this method cannot be translated
into a store expression.
You can't use regular function calls in a query definition like that. LINQ needs expression trees, it can't analyze compiled functions and magically translate that to SQL. Read this for a more elaborate explanation
The techniques used in the cited article are incorporated in linqkit (factoring out predicates) and might be of help, though I'm not sure you can use the same technique for managing projections, which is what you seem to want.
The more fundamental question you should ask yourself here IMHO is whether you really need this extra mapping layer? It seems like you're implementing something that EF is already perfectly capable of doing for you...
Try making your MapUser method static.

Resources