akd
akd

Reputation: 6758

How to retrieve an object by ID entity Framework?

I followed up this tutorial here To implement Repository pattern with Autofac dependency injector and Unit Of Work.

Now I am trying to retrieve an artist Object from database.

With Dbcontext it was as easy as just using _db.Artists.Find(id) Now because I implemented Generic Repository also new Repository patern. I am not sure what should be the query

in my artist controller

 return View(this._artistDetailsRep.SingleOrDefault(p => p.ArtistID= id));

which complains that an experssion tree cannot an assignment operator.

here is the generic method :

 public virtual TEntity SingleOrDefault(
        Expression<Func<TEntity, bool>> where, params Expression<Func<TEntity, object>>[] includeProperties)
    {
        IQueryable<TEntity> query = this.AsQueryable();
        query = PerformInclusions(includeProperties, query);
        return query.SingleOrDefault(where);
    }

How should be my query to retrieve the object that I knot the id of it?

Thanks

Upvotes: 1

Views: 110

Answers (1)

nemesv
nemesv

Reputation: 139758

Your issue is not related to EF or Autofac or to the repository pattern but you are misusing the SingleOrDefault: you need to use double equals == instead of a single equals sign =:

return View(this._artistDetailsRep.SingleOrDefault(p => p.ArtistID == id));

An single equals sign = means assignment (which is invalid in this context) but in your case you need comparasion so you need double equals ==.

In this case your SingleOrDefault call will translates to: "give me the only artist with the ArtistID equals id or null if the artist does not exists."

Upvotes: 3

Related Questions