验证独特属性方法
我试图编写一个从 CustomValidator 调用的方法来确定字符串属性是否唯一。我试图使其通用,以便我可以为许多不同的字符串属性重用代码。我正在使用反射。这看起来是一种太复杂的方法吗?是否有更好的方法可以做到这一点,但仍然使其通用?
public virtual bool IsPropertyUnique(T entity, string newValue, string propertyName)
{
var values =
Context.GetTable<T>.Where(e => string.Equals(e.GetType().GetProperty(propertyName).GetValue(e, null), newValue)).ToList();
return values.Count == 0;
}
I was trying to write a method to be called from a CustomValidator to determine whether a string property was unique or not. I was trying to make it generic so that I can reuse the code for many different string properties. I'm using reflection. Does this seem like a way too complicated way of doing this? Does there happen to be a better way of doing this but still making it generic?
public virtual bool IsPropertyUnique(T entity, string newValue, string propertyName)
{
var values =
Context.GetTable<T>.Where(e => string.Equals(e.GetType().GetProperty(propertyName).GetValue(e, null), newValue)).ToList();
return values.Count == 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一项可能的改进:
One possible improvement:
由于这是 LINQ to SQL,因此您需要提供它可以理解并解析为 SQL 的内容。此刻它会看到一堆疯狂的倒影并开始哭泣。
您可以更改方法调用的形式
,这样就可以正常工作。
如果你想保留你的方法签名,你必须深入研究表达式树。基本上,您想要创建以下表达式,以便 LINQ to SQL 可以执行“哦,是的,这是与属性“Bar”相对应的列上的 where 子句”
要重新创建,您需要执行以下操作
在这里还使用 Any 而不是Where可以稍微提高性能,因为它不必从数据库中加载匹配的记录(它只会执行 IF EXISTS 代替)。
Since this is LINQ to SQL you need to provide something that it can understand and parse into SQL. At the moment it's going to see a bunch of crazy reflection and start to cry.
You could change the form of your method call to
and that'd work just fine.
If you wanted to preserve your method signature you have to get down and dirty with expression trees. Basically you want to create the following expression so LINQ to SQL can go "oh yeah that's a where clause on the column that corresponds to the property 'Bar'"
To recreate you'd need to do the following
Also using Any instead of Where here can be slightly more performant as it doesn't have to load the matching records out of the DB (it'll just do a IF EXISTS instead).