EF Codefirst验证独特属性? [英] EF Codefirst validate unique property?

查看:150
本文介绍了EF Codefirst验证独特属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好奇有关如何有效地验证CodeFirst模型的给定属性是唯一的。典型的例子是成员的用户名或显示名称。



传统上,我可以通过在数据库中设置唯一约束,或者通过在尝试插入操作期间进行查找来执行此操作。我知道如何在数据库本身之后手动添加这些东西,只是希望看到是否有办法作为框架提供的模式映射的一部分。



更新
我发现我可以覆盖DbContext上的ValidateEntity方法,这在概念上将允许我做一个查找,然后使该对象无效保存。我仍然很想知道是否有办法在数据库中应用Unique约束或类似的方式。

解决方案

Code First(和EF)一般而言, 本身不支持唯一约束。在 这篇文章 我展示了一种创建它们的方法,同时你的数据库被Code First创建(通过SQLCommand方法在一个自定义的初始化程序类),但它并没有真正的区别,手动创建它自己。另一种方法是你建议的 ValidateEntity ,但是我仍然会在数据库上创建唯一的约束。


Curious about how to efficiently validate that a given property of a CodeFirst model is unique. Classic example being a member's username or display name.

Traditionally I might do this by setting a Unique constraint in the database, or alternatively by doing a lookup during an attempted insert operation. I know how to manually add these things in the DB itself after generation, just wanting to see if there's a way to do it as part of the schema mapping provided by the framework.

UPDATE I found that I can override the ValidateEntity method on the DbContext, which conceptually would allow me to do a lookup and then invalidate the object to prevent the save. I'd still be curious to know if there's a way to apply a Unique constraint or similar in the database

解决方案

Code First (and EF in general) still does not natively support unique constraints. In this post I showed one way to create them at the same time that your database is get created by Code First (via SQLCommand method in a custom Initializer class) but it's not really different from manually creating it yourself. The other way is ValidateEntity which you've suggested, but I would still create the unique constraints on the database anyways.

这篇关于EF Codefirst验证独特属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆