![](/img/trans.png)
[英]Declaring a property in a model that will not get generated as a column in the database by Entity Framework migrations
[英]Generated property from db column in Entity Framework. Why an if condition is not there in setter of property in case of column allow NULL
如果column allow不允许db中的NULL,则Entity Framework中生成的属性的setter中的条件为if (_ColumnName != value
)
有什么用?
为什么从允许NULL的列生成的setter中缺少此条件?
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Address1
{
get
{
return _Address1;
}
set
{
if (_Address1 != value) // This condition is only for columns which are not null in db. Why this is not needed for nullable columns.
{
OnAddress1Changing(value);
ReportPropertyChanging("Address1");
_Address1 = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("Address1");
OnAddress1Changed();
}
}
}
private global::System.String _Address1;
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String Address2
{
get
{
return _Address2;
}
set
{
// NO IF CONDITION HERE LIKE IT IS IN PROPERTY WHICH DON'T ALLOW NULL (ABOVE PROPERTY ADDRESS1)
OnAddress2Changing(value);
ReportPropertyChanging("Address2");
_Address2 = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("Address2");
OnAddress2Changed();
}
}
private global::System.String _Address2;
不,如果条件与该属性是否为Nullable无关。 仅当属性为EntityKey时才会生成它。
深入研究ADO.NET EntityObject Generator T4模板 (这是默认的代码生成工具,它是VS 2010用于生成实体对象的工具)揭示了这一点:
if (ef.IsKey(primitiveProperty))
{
if (ef.ClrType(primitiveProperty.TypeUsage) == typeof(byte[]))
{
#>
if (!StructuralObject.BinaryEquals(<#=code.FieldName(primitiveProperty)#>, value))
<#+
}
else
{
#>
// Here it inject the if condition:
if (<#=code.FieldName(primitiveProperty)#> != value )
<#+
}
#>
{
<#+
PushIndent(CodeRegion.GetIndent(1));
}
#>
<#=ChangingMethodName(primitiveProperty)#>(value);
ReportPropertyChanging("<#=primitiveProperty.Name#>");
<#=code.FieldName(primitiveProperty)#> = StructuralObject.SetValidValue(value<#=OptionalNullableParameterForSetValidValue(primitiveProperty, code)#>);
ReportPropertyChanged("<#=primitiveProperty.Name#>");
<#=ChangedMethodName(primitiveProperty)#>();
<#+
if (ef.IsKey(primitiveProperty))
{
PopIndent();
#>
}
<#+
}
#>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.