Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Entities - How to return a single string value from entity

I am working in asp mvc 3 app. I have a model/entity called History. I have a linq query that returns one value. Depending on what I do, I either get a "Object not set to an instance" error in the controller when the method is called, or I get a "cannot implicitly convert from string to type Models.History." So I am looking for assistance in resolving, do I just need to cast it or something?

Here is the method that gives the 'object not set' error:

public string GetPastAbuseData(int Id)
{

  var query = (from h in _DB.History
              where h.ApplicantId.Equals(Id)
              select h.AbuseComment).FirstOrDefault();

  return query.ToString();
 }

Controller: vm.HistoryModel.AbuseComment = repo.GetPastAbuseData(Id);

And if I change the method type from string to History I get the 'cannot convert' error:

public History GetPastAbuseData(int Id)
{
    return (from h in _DB.History
            where h.ApplicantId.Equals(Id)
            select h.AbuseComment).SingleOrDefault();
}

Thank you for your time.

like image 525
BattlFrog Avatar asked Nov 02 '12 17:11

BattlFrog


People also ask

How do I Select a single value in Entity Framework?

Using Select.Single and SingleOrDefault.: table where c.id== id select new { Name = c.Name, }; var query = (from c in db. table where c.id== "Classic id" select new { c. xyz }).

Which LINQ method returns a single object?

You can use the SingleOrDefault method if you are sure there will be only a single item or null yields from your where condition.

Which LINQ method returns a Boolean value?

In LINQ, quantifier operators are used to returning a boolean value which shows that whether some or all elements satisfies the given condition.


1 Answers

You are selecting AbuseComment property (which is string) from HistoryObject. Thus your code tries to convert string to History. Just return whole History entity:

public History GetPastAbuseData(int Id)
{
    return (from h in _DB.History
            where h.ApplicantId.Equals(Id)
            select h).SingleOrDefault();
}

Also in first case query will be of string type. You don't need to call ToString on this variable. Even more, when you fall into OrDefault() case, you will have NullReferenceException.

public string GetPastAbuseData(int Id)
{
  return (from h in _DB.History
          where h.ApplicantId.Equals(Id)
          select h.AbuseComment).FirstOrDefault();
}
like image 84
Sergey Berezovskiy Avatar answered Sep 19 '22 11:09

Sergey Berezovskiy