LINQ to Entities - How to return a single row value from an object

I work in asp mvc 3 app. I have a model / object called "History". I have a linq query that returns a single value. Depending on what I am doing, I either get the error message "The object is not set to an instance" in the controller when the method is called, or I get "cannot implicitly convert the string from string to Models.History type". So I’m looking for help in resolving, do I just need to give it up or something?

Here is the method that gives the error "object not installed":

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 type of the method from a string to "History", I get the error "can not convert":

 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.

+6
source share
3 answers

You select the AbuseComment property (which is a string) from HistoryObject . So your code is trying to convert a string to History . Just return the whole entity History :

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

Also in the first case, query will have a string type. You do not need to call ToString for this variable. Moreover, when you get into the OrDefault() case, you will have a NullReferenceException .

 public string GetPastAbuseData(int Id) { return (from h in _DB.History where h.ApplicantId.Equals(Id) select h.AbuseComment).FirstOrDefault(); } 
+11
source

Your first example is fine, you just need to check for null.

 public string GetPastAbuseData(int Id) { var query = (from h in _DB.History where h.ApplicantId.Equals(Id) select h.AbuseComment).FirstOrDefault(); return query == null ? string.empty : query; } 
+4
source

You can use a null coalescing operator that will check if it is null and returns string.Empty if it is zero. ?? Operator

 public string GetPastAbuseData(int Id) { return _DB.History.FirstOrDefault(h=>h.ApplicantId.Equals(Id)).Select(h=>h.AbuseComment) ?? string.Empty; } 
+2
source

All Articles