Get Single MembershipUser from MembershipUserCollection

99封情书 提交于 2019-12-24 10:45:01

问题


I'm learning ASP.Net MVC3 EF4 by coding a sample app. I'm using the standard Membership Provider. I have the requiresUniqueEmail="true" in the Membership provider so no more than 1 email per MembershipUser.

I want to find a particular user by their email address. There is a function that helps:

MembershipUserCollection users = Membership.FindUsersByEmail(model.Email);

Since I have unique emails, how do I get the MembershipUser from the MembershipUserCollection? I know I can do a foreach loop:

foreach (MembershipUser user in users)
{
username = user.UserName;
}

but is there a quicker way of just accessing the first row?

This doesn't work: MembershipUser user = users[0];

but that is kind of what I'm looking for.

Thanks!!

UPDATE: This works but I'm still interested in an answer to the above:

string username1 = Membership.GetUserNameByEmail(model.Email);
MembershipUser user = Membership.GetUser(username1);

回答1:


since you have unique email for each users why are you using MembershipUserCollection Class

rather you can directly get it using

    string userName = Membership.GetUserNameByEmail(model.Email);

    MembershipUser oMu = Membership.GetUser(userName); 

oMu object will give you all the properties of the user with email address you have passed in GetUserNameByEmail(model.Email)

EDIT based on update in question

I think it is irrelevant to load a collection where you have only single record, memory consumption will be more as compared to string username (which is used in my example), plus you have problems in finding the single record (where you are using loop, unnecessary delay in fetching the details). Additionally line of code is reduced (compiling the code become more easy and faster.)




回答2:


Try using the First() Linq extension method as follows:

using System.Linq;
...
var user = Membership.FindUsersByEmail(model.Email).Cast<MembershipUser>.First();

(You may also cast to your custom MembershipUser subclass if you happen to use one).



来源:https://stackoverflow.com/questions/10662397/get-single-membershipuser-from-membershipusercollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!