简体   繁体   中英

First method of Linq giving error

In my webmethod of my WCF rest service i am trying to find record using Linq's First method like below

  [WebInvoke(UriTemplate = "UpdateProductObject", Method = "PUT")]
    public Result UpdateProductObject(ProductObjectToSave prodSave)
    {

        IUnitOfWork unitOfWork = new UnitOfWork((IObjectContext)_objectSetFactory);
        var versions = prodSave.VersionDetails;

        foreach (var versionDetail in versions)
        {
            var detail = versionDetail;

            var dbVersionentity = _productVersionEntityRepository.First(x => x.Id == detail.Id);

            if (detail.Id  < 0)
            {

                dbVersionentity.Id = GetNextTableId("vProductVersion");

            }

            dbVersionentity.Name = detail.Name;
            dbVersionentity.Code = detail.Name;

            if (detail.Id > 0){

            _productVersionEntityRepository.Update(dbVersionentity);
            }
            else
            {
                _productVersionEntityRepository.Insert(dbVersionentity);
            }


        }


        try
        {
            unitOfWork.Commit();
        }
        catch (Exception e)
        {

            return new Result() { Error = e.Message };
        }

        return new Result() { Error = "Record updated successfully" };

    }

The "_productVersionEntityRepository" is defined as below in my service.

 private readonly Repository<ProductVersionEntity> _productVersionEntityRepository;

When there are no records it throws exception "Sequence contains no elements" . I have done some finding that we can use FirstOrDefault method. But somehow i am not getting that option to use FirstOrDefault. I am really new to this so may be i have missed some links where solution could have been described. Please help me or suggest me other way to do some error handling if First method fails

That's the way that First() works, it will throw an exception if the element can't be found. You can use FirstorDefault() instead and check if the element is null .

Edit: I realised that you're using a custom repository. If you have access to the source code, I advise you to add a new method called .FirstOrDefault() that will take as parameter a predicate and returns null if no entities are found.

Edit 2: Add this method to your repository:

T FirstOrDefault(Expression<Func<T, bool>> where, params Expression<Func<T, object>>[] includeProperties) 
{ 
    IQueryable<T> query = AsQueryable(); 
    query = PerformInclusions(includeProperties, query); 

    return query.FirstOrDefault(where); 
}

Then you can do something like this in your code:

foreach (var versionDetail in versions)
{
    bool isNew = false;
    var detail = versionDetail;

    var dbVersionentity = _productVersionEntityRepository.FirstOrDefault(x => x.Id == detail.Id);

    // not found in database
    if(dbVersionentity == null)
    {
        isNew = true;

        // create entity here
        dbVersionentity = new .....; 

        // you don't need to do this if id is auto-generated, 
        // i.e. Identity column in SQL Server
        dbVersionentity.Id = GetNextTableId("vProductVersion");
    }

    dbVersionentity.Name = detail.Name;
    dbVersionentity.Code = detail.Name;


    if (isNew)
    {
        _productVersionEntityRepository.Insert(dbVersionentity);
    }
    else
    {
        _productVersionEntityRepository.Update(dbVersionentity);
    }
}

尝试

var dbVersionentity = _productVersionEntityRepository.Where(x => x.Id == detail.Id).FirstOrDefault();

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