C# 数据库优先方法中的唯一约束
我有许多独特的约束数据库 我知道实体框架对它们一无所知。所以我需要手动将它们添加到模型中。但是在C# 数据库优先方法中的唯一约束,c#,sql-server,entity-framework,C#,Sql Server,Entity Framework,我有许多独特的约束数据库 我知道实体框架对它们一无所知。所以我需要手动将它们添加到模型中。但是在 System.ComponentModel.DataAnnotations 没有唯一的关键字 我创建了新属性: [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class UniqueKeyAttribute : Attribute { } 并将其添加到我的模型
System.ComponentModel.DataAnnotations
没有唯一的关键字
我创建了新属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class UniqueKeyAttribute : Attribute
{
}
并将其添加到我的模型中:
[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; }
}
甚至
Model.IsValid
始终返回true,即使表中已经存在该值
我应该编写什么代码来更改此行为 对于您的问题,一个简单的答案是Entity framework不支持唯一键,因此唯一的方法是在数据库中设置唯一约束(正如您实际所做的那样)。如果缺少唯一性,那么当您尝试在数据库中插入/更新新行时,将抛出适当的异常,然后您可以捕获并处理这些异常 你的UniqueKeyAttribute的逻辑是什么?或者这个像你粘贴的一样是空的吗?您是否知道检查唯一性需要调用DB(对于其他数据注释属性,如Required、MaxLength等,情况并非如此)?谢谢。此时此刻,你可以看到它是什么样子。空的。