据我所知,IValidatableObject它用于以一种方式验证对象,让人们相互比较属性.
我仍然希望有属性来验证单个属性,但我想在某些情况下忽略某些属性的失败.
我是否试图在下面的情况下错误地使用它?如果不是我如何实现这个?
public class ValidateMe : IValidatableObject
{
[Required]
public bool Enable { get; set; }
[Range(1, 5)]
public int Prop1 { get; set; }
[Range(1, 5)]
public int Prop2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!this.Enable)
{
/* Return valid result here.
* I don't care if Prop1 and Prop2 are out of range
* if the whole object is not "enabled"
*/
}
else
{
/* Check if Prop1 and Prop2 …Run Code Online (Sandbox Code Playgroud) 有没有办法沿着这些方向做点什么?
interface Iface
{
[anytype] Prop1 { get; }
[anytype] Prop2 { get; }
}
class Class1 : Iface
{
public string Prop1 { get; }
public int Prop2 { get; }
}
class Class2 : Iface
{
public int Prop1 { get; }
public bool? Prop2 { get; }
}
Run Code Online (Sandbox Code Playgroud)
我不关心属性的类型,我只需要可用的属性.这不必使用接口实现,仅使用它作为示例.
我想在模型上使用延迟加载集合,但我希望通过单独的方法完成添加/删除功能.所以像这样:
class Model
{
protected virtual ICollection<Something> _somethings { get; set; }
public IEnumerable<Something> Somethings
{
get { return _somethings; }
}
public void AddSomething(Something thingToAdd)
{
/* logic */
_somethings.Add(thingToAdd);
}
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何为此配置映射.我研究了使用配置类:EntityConfiguration.但由于该属性受到保护,我无法弄清楚如何在其上设置配置.有没有办法完成我在这里要做的事情?