简体   繁体   English

数据库优先方法的唯一约束

[英]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.

相关问题 EF迁移数据库优先方法? - EF Migrations for Database-first approach? 使用ViewModel数据库优先方法将表保存在数据库中 - Saving Table in database using a ViewModel database-first approach 实体框架中没有自动生成代码的数据库优先方法 - Database-first approach in Entity Framework without auto generated code EDMX使用EF中的数据库优先方法不存在任何关系 - EDMX has no relations present using the database-first approach in EF 数据库优先方法中的Linq-to-SQL与实体框架 - Linq-to-SQL vs Entity Framework in database-first approach 如何以数据库优先的方法仅更新一个 model? - How to update only one model in a database-first approach? 实体框架数据库优先方法有条件地插入数据 - Entity Framework database-first approach conditionally insert data 使用数据库优先方法MVC3向模型添加新字段不会从数据库中提取数据 - Adding a new field to Model with Database-First Approach MVC3 does not pull data from database 在实体框架中刷新使用数据库优先方法模型创建的实体中的数据 - Refresh the data in entity created using database-first approach model in Entity Framework 在“实体框架”数据库优先方法中,将“默认值1”设置为EntityName(状态) - Set Default Value 1 to an EntityName (Status) in Entity Framework database-first approach
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM