0

I am trying to figure out how to check a property of my EF 6 model to see if it contains a value or not. The property is an INt64 so I can't use string.Empty and I can not just compare it to an empty string with out converting it. How can I modify this check so it will return "No" if there is no value in "LogoFileID"?

HasLogo = (section.LogoFileID != string.Empty) ? "Yes" : "No";

Here is my model

public class Section
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Int16 ID { get; set; }

    public Int64? LogoFileID { get; set; }

    [Required, MaxLength(250), Column(TypeName = "varchar")]
    public string RouteName { get; set; }

    [Required, MaxLength(15), Column(TypeName = "varchar")]
    public string Type { get; set; }

    [Required]
    public string Title { get; set; }

    public string Synopsis { get; set; }

    [ForeignKey("LogoFileID")]
    public virtual File Logo { get; set; }
}
Matthew Verstraete
  • 6,335
  • 22
  • 67
  • 123
  • One other thing you should change in your example above is to use `string.IsNullOrEmpty(section.LogoFileID)`, of course swapping for a string. That way you don't have to have a separate null check. – krillgar Dec 12 '13 at 20:02

2 Answers2

4
HasLogo = (section.LogoFileID.HasValue) ? "Yes" : "No";

You're using a nullable int64 type so a HasValue property is exposed giving you what you want.

Documentation for nullable type overview: http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx

Khepri
  • 9,547
  • 5
  • 45
  • 61
1

Since your int64 is nullable my preference would be to check for a null value.

HasLogo = (section.LogoFileId != null) ? "Yes" : "No";

Update: Originally this answer suggested that checking whether the logo property was null was another way to return the HasLogo value as pointed out by Tim S. in the comments below this would cause a DB call for every section tested.

bebleo
  • 326
  • 4
  • 12
  • 1
    I'd think checking `Logo` could make an unneeded DB call (one for each `section`). – Tim S. Dec 12 '13 at 20:09
  • Verified that yes, it does do another DB call for each section. Will edit my answer to reflect this. – bebleo Dec 12 '13 at 21:00