有没有办法让 EF 在设置属性值而不是属性 setter 时使用支持字段?
我问的原因是,在 setter 中可能有一个逻辑,我不想每次从数据库返回对象时都调用它。
例如:
class SomeClass
{
int _prop;
public Prop
{
get { return _prop;}
set
{
CustomValidation(value);
_prop = value;
}
}
}
在上面的示例中,CustomValidation() 在设置值时被调用。从数据库返回对象时无需调用此验证,因为这些对象在创建/验证时已验证。
最佳答案
不,目前您不能将列直接映射到字段。去年已经讨论过了,但我不确定这是否会成为 future 版本的一部分。检查这个article进一步解释。这是设计的代码摘录。
modelBuilder .Entity<Blog>() .Property(b => b.Title) .UseBackingField("_theTitle");
解决方法是创建域对象或添加将在前端用于创建或验证的未映射属性。
public int Prop { get; set; }
[NotMapped]
public int ValidatedProp // bind to this property in the front end
{
get { return Prop; }
set
{
CustomValidation(value);
Prop = value;
}
}
关于.net - EF : using backing field for setting property value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25339955/