简体   繁体   中英

Entity framework repeating records

I am working on an Entity framework project,In which i have created and entity class of a table

and i am returning its records, below is my method of retrieving records

 public UserResource GetData(long Id)
        {
            try
            {

                return dataContext.UserResources.Where(r => r.UserID == Id && r.Resource.IsActive == true).FirstOrDefault();


            }
            catch (Exception ex)
            {
              throw ex;
            }
        }

and then on controller i am adding it to List

List<UserResource> objlst = new List<UserResource>();
for(int i=0;i<100;i++)
{
var data = objResourceRepository.GetData(userIds[i].UserID);
if (data != null)
objlst.Add(data);
}

userIds are coming from a separate Method The problem i am having is that the data is adding twice ie one record is adding two times, what is the problem with this code and what alternative should i use GetData() method?

Either you have duplicate records for the same useId in your UserResources table, or you have duplicated userIds in your userIds array.

Either way, going to the DB separately for each of 100 records seems a very inefficient way of doing things. It would be better, at least, to pass through the array of use arrays to the GetData function, and use an 'in' clause in there. Then have your GetData function return an enumeration of UserResources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM