简体   繁体   English

检查EF6模型的属性是否具有值?

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

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. 我试图弄清楚如何检查我的EF 6模型的属性以查看其是否包含值。 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. 该属性是INt64,所以我不能使用string.Empty并且我不能只将其与空字符串进行比较而不进行转换。 How can I modify this check so it will return "No" if there is no value in "LogoFileID"? 如何修改此检查,以便在“ 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; }
}
HasLogo = (section.LogoFileID.HasValue) ? "Yes" : "No";

You're using a nullable int64 type so a HasValue property is exposed giving you what you want. 您正在使用可为null的int64类型,因此公开了HasValue属性,可为您提供所需的内容。

Documentation for nullable type overview: http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx 可为空的类型概述的文档: http : //msdn.microsoft.com/zh-cn/library/1t3y8s4s.aspx

Since your int64 is nullable my preference would be to check for a null value. 由于您的int64是可为空的,因此我希望检查是否为空值。

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. 更新:最初,此答案表明,检查徽标属性是否为null是Tim S指出的返回HasLogo值的另一种方法。这在下面的注释中将导致对每个测试的部分进行DB调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM