Checking property of EF6 model to see if it has a

2019-09-09 23:18发布

问题:

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; }
}

回答1:

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



回答2:

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.