问题
I have a table like the following:
[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; }
}
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?
回答1:
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; }
}
来源:https://stackoverflow.com/questions/36927568/enforce-one-of-two-columns-not-be-null-with-entity-framework-6