Checking property of EF6 model to see if it has a value or not?

不问归期 提交于 2020-01-17 01:39:07

问题


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.



来源:https://stackoverflow.com/questions/20552909/checking-property-of-ef6-model-to-see-if-it-has-a-value-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!