我想知道Entity Framework Core 2代码第一种方法中是否存在唯一约束的数据注释?
答案 0 :(得分:6)
在EF Core中您只能在流畅的API中使用扩展方法HasAlternateKey
。 无数据注释可实现唯一约束。
这篇MS doc文章 - Alternate Keys (Unique Constraints) - 将解释如何使用以及存在哪些其他可能性。
以上链接的简短示例:
class MyContext : DbContext
{
public DbSet<Car> Cars { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>()
.HasAlternateKey(c => c.LicensePlate)
.HasName("AlternateKey_LicensePlate");
}
}
class Car
{
public int CarId { get; set; }
public string LicensePlate { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}
此外,还可以定义唯一索引。因此,在EF Core中,您必须在流畅的API中使用扩展方法HasIndex
(无数据注释)。
在这篇MS doc文章 - Indexes中 - 您将找到更多信息。
这是一个独特索引的例子:
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasIndex(b => b.Url)
.IsUnique();
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
答案 1 :(得分:5)
我编写了一个Attribute类,它可以让您装饰EF Core Entity类的属性以导致生成唯一键(不使用Fluent API)。
using System;
using System.ComponentModel.DataAnnotations;
/// <summary>
/// Used on an EntityFramework Entity class to mark a property to be used as a Unique Key
/// </summary>
[AttributeUsageAttribute(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class UniqueKeyAttribute : ValidationAttribute
{
/// <summary>
/// Marker attribute for unique key
/// </summary>
/// <param name="groupId">Optional, used to group multiple entity properties together into a combined Unique Key</param>
/// <param name="order">Optional, used to order the entity properties that are part of a combined Unique Key</param>
public UniqueKeyAttribute(string groupId = null, int order = 0)
{
GroupId = groupId;
Order = order;
}
public string GroupId { get; set; }
public int Order { get; set; }
}
在DbContext.cs文件的OnModelCreating(modelBuilder)方法内,添加以下内容:
// Iterate through all EF Entity types
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
#region Convert UniqueKeyAttribute on Entities to UniqueKey in DB
var properties = entityType.GetProperties();
if ((properties != null) && (properties.Any()))
{
foreach (var property in properties)
{
var uniqueKeys = GetUniqueKeyAttributes(entityType, property);
if (uniqueKeys != null)
{
foreach (var uniqueKey in uniqueKeys.Where(x => x.Order == 0))
{
// Single column Unique Key
if (String.IsNullOrWhiteSpace(uniqueKey.GroupId))
{
entityType.AddIndex(property).IsUnique = true;
}
// Multiple column Unique Key
else
{
var mutableProperties = new List<IMutableProperty>();
properties.ToList().ForEach(x =>
{
var uks = GetUniqueKeyAttributes(entityType, x);
if (uks != null)
{
foreach (var uk in uks)
{
if ((uk != null) && (uk.GroupId == uniqueKey.GroupId))
{
mutableProperties.Add(x);
}
}
}
});
entityType.AddIndex(mutableProperties).IsUnique = true;
}
}
}
}
}
#endregion Convert UniqueKeyAttribute on Entities to UniqueKey in DB
}
也在您的DbContext.cs类中,添加以下私有方法:
private static IEnumerable<UniqueKeyAttribute> GetUniqueKeyAttributes(IMutableEntityType entityType, IMutableProperty property)
{
if (entityType == null)
{
throw new ArgumentNullException(nameof(entityType));
}
else if (entityType.ClrType == null)
{
throw new ArgumentNullException(nameof(entityType.ClrType));
}
else if (property == null)
{
throw new ArgumentNullException(nameof(property));
}
else if (property.Name == null)
{
throw new ArgumentNullException(nameof(property.Name));
}
var propInfo = entityType.ClrType.GetProperty(
property.Name,
BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (propInfo == null)
{
return null;
}
return propInfo.GetCustomAttributes<UniqueKeyAttribute>();
}
在Entity.cs类中的用法:
public class Company
{
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CompanyId { get; set; }
[Required]
[UniqueKey(groupId: "1", order: 0)]
[StringLength(100, MinimumLength = 1)]
public string CompanyName { get; set; }
}
您甚至可以在多个属性中使用它来在表中的多个列之间形成唯一键。 (请注意,先使用“ groupId”,然后再使用“ order”)
public class Company
{
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CompanyId { get; set; }
[Required]
[UniqueKey(groupId: "1", order: 0)]
[StringLength(100, MinimumLength = 1)]
public string CompanyName { get; set; }
[Required]
[UniqueKey(groupId: "1", order: 1)]
[StringLength(100, MinimumLength = 1)]
public string CompanyLocation { get; set; }
}
答案 2 :(得分:4)
为了更新,现在有一个代码优先注释。
[Index(nameof(MyProperty), IsUnique = true)] // using Microsoft.EntityFrameworkCore
public class MyClass
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
[StringLength(255), Required]
public string MyProperty { get; set; }
}
答案 3 :(得分:0)
在 DbContext.cs
文件中,在 OnModelCreating(modelBuilder)
方法中,在最后一个 ForEach
上,我有 .OrderBy(o => o.Order)