[英]Unique constraint in database-first approach
I'm have database with many unique constraints. 我有许多独特约束的数据库。
I'm aware of that entity framework doesn't know anything about them. 我知道该实体框架对它们一无所知。 So I need to add them to the model manually.
因此,我需要将它们手动添加到模型中。 But in
但在
System.ComponentModel.DataAnnotations
There is no Unique keyword. 没有唯一关键字。
I created new attribute: 我创建了新属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class UniqueKeyAttribute : Attribute
{
}
and added it to my model: 并将其添加到我的模型中:
[MetadataType(typeof(DeviceInstance))]
public partial class DeviceInstance
{
public int Id { get; set; }
[Required]
public int DeviceId { get; set; }
[Required]
[UniqueKey]
[MaxLength(50)]
public string SerialNo { get; set; }
[Required]
public System.DateTime CreationDate { get; set; }
}
Even that Model.IsValid
is always returning true even if there is already that value in the table. 即使该
Model.IsValid
始终返回true,即使表中已经存在该值。
What code should I write to change this behavior? 我应该写什么代码来改变这种行为?
A simple answer to your question is that Entity framework doesn't support unique keys so the only way is to set the unique constraint is in in the database (as you in fact did). 对于您的问题的一个简单答案是,实体框架不支持唯一键,因此唯一的方法是在数据库中设置唯一约束(就像您实际上所做的那样)。 By doing so appropriate exceptions will be thrown when you try to insert/update new rows in the DB in case of a lack of uniqueness, which you can then catch and handle.
这样,当您在缺乏唯一性的情况下尝试在数据库中插入/更新新行时,将引发适当的异常,然后您可以捕获并处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.