【发布时间】:2014-09-12 12:26:20
【问题描述】:
我正在使用 EF(db first)并尝试使用下一个代码在表中添加新行:
var user = new User();
//Some logic to fill the properties
context.Users.AddObject(user);
context.SaveChanges();
在 EF 上保存更改之前,我想验证是否已填充所有必需的(非 null 且没有默认值)属性。我怎样才能获得所有这些字段?
我尝试了几种方法,但无法达到所需的结果。最后一次尝试是这样的:
var resList = new List<PropertyInfo>();
var properties = type.GetProperties(BindingFlags.DeclaredOnly |
BindingFlags.Public |
BindingFlags.Instance).Where(p => !p.PropertyType.IsGenericType);
foreach (var propertyInfo in properties)
{
var edmScalarProperty =
propertyInfo.CustomAttributes.FirstOrDefault(
x => x.AttributeType == typeof (EdmScalarPropertyAttribute));
var isNullable = true;
if (edmScalarProperty != null)
{
var arg = edmScalarProperty.NamedArguments.FirstOrDefault(x => x.MemberName == "IsNullable");
if (arg != null)
{
isNullable = (bool) arg.TypedValue.Value;
}
}
if (!isNullable)
{
resList.Add(propertyInfo);
}
}
return resList;
【问题讨论】:
-
在您的 edmx 文件上使用自定义 .tt 生成一个不可为空的无默认属性列表会不会更容易?我不明白你怎么能从那里得到带有“默认值”的属性(但我可能会错过一些东西)。
标签: c# entity-framework