使用Entity Framework 6强制两列之一不为NULL [英] Enforce one of two columns not be NULL with Entity Framework 6

查看:101
本文介绍了使用Entity Framework 6强制两列之一不为NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下表:

[Table("tblStore")]
public class Store
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

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

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

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

    [Required]
    public DateTime Created { get; set; }
}

我需要强制指定Option1或Option2(不为null) 。有人可以建议使用EF 6的方法吗?

I need to enforce that either Option1 or Option2 be specified (not null). Can someone please suggest a way to do that with EF 6?

推荐答案

您可以做一个技巧:将新属性添加到POCO类,这将是 Option1 Option2 串联的结果,并设置为此属性(将其命名为选项)属性 [必需] 。当然,我们需要从 Option1 Option2 属性中删除此属性,以便可以将其分配给 null 值。现在,如果 Option1 Option2 没有值,则 Options 也将为空白,由于具有 [Required] 属性,当您尝试将此实体插入数据库时​​,将引发EF的错误:

You can do one trick: add new property to your POCO class, that will be result of concatenation of Option1 and Option2 and set to this property(let call it Options) attribute [Required]. Of course, we need to remove this attribute from Option1 and Option2 properties to make it possible assign to them null values. Now, if Option1 and Option2 will not have values, Options also will be blank and due to [Required] attribute on it, EF's error will be thrown, when you will attempt to insert this entity into database:

public class Store
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

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

    public string Option1 { get; set; }        
    public string Option2 { get; set; }

    [Required]
    public string Options { get { return Option1 + Option2; } private set { } }

    [Required]
    public DateTime Created { get; set; }
}

这篇关于使用Entity Framework 6强制两列之一不为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆