开发者

Linq query does not populate a property

开发者 https://www.devze.com 2023-04-01 02:06 出处:网络
I have a linq query that is running inside a method, which is being called inside a for loop: var allUsers = userRepository.getAll();

I have a linq query that is running inside a method, which is being called inside a for loop:

var allUsers = userRepository.getAll();

foreach (var user in allUsers)
            {
                UserWithExtras userWithExtras = createUserWithExtrasFromLoginName(user.LoginName);
                int userId = userWithExtras.userId;


            }

--------------------------------------------
public static createUserWithExtrasFromLoginName(string loginName){
    var user = (from u in userDb.Users
        where u.Login.ToLower().Equals(login.ToLower())
        select u);
    int a = u.userId;
}

I have 15 users in my database, for the first 10 users with IDs from 1 to 10, everything is retrieved properly, after that, the IDs are not populated properly anymore, i.e. in order, the retrieved Users have these IDs: 1,2,3,4,5,6,7,8,9,10,11,10,10,8,0

I have traced the issue in the query in createUserWithExtrasFromLoginName, and the last retrieved object actually has the ID 0, eventhough in the db the ID is 15.

I have checked the dbml file, and made sure Delay Loaded is set to false for this property. Both in dbml file and in the database the userId property is set to be a primary key.

any help would be really 开发者_如何学运维appreciated.


Thanks anyone who tried to answer this, I tried answering my own question yesterday but stackoverflow didn't let me, I basically dropped the Users table from the dbml file and re-inserted it again, and the issue was fixed.


The method where you're using the LINQ query doesn't specify a return value. From the looks of your code, that method should return a UserWithExtras object.


From what you've posted, it looks like you could replace all of that with a single LINQ query. More details might be helpful.

var userIds = from u in userDb.Users 
               where u.Login.ToLower().Equals(login.ToLower()) 
               select u.userId;

This assumes that userRepository and userDb are accessing the same store. In which case, there seems to be some confusion. By querying for all users and then iterating over users and querying all users for the userId on the login name you'll be performing WAY more work than needed (see cartesian product).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号