[英]EF Core - unique, indexed, auto-generated guid column that is not the primary key
I am migrating from .NET EF to EF CORE.我正在从 .NET EF 迁移到 EF CORE。 I have a working solution that automatically generates a unique GUID aside from its primary key.
我有一个有效的解决方案,除了主键之外,它还会自动生成一个唯一的 GUID。 Below is the solution.
下面是解决方案。
[Key, Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Index(IsUnique = true)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid TenantId { get; set; }
However, when i tried to migrate to EF Core, i am getting an error message when inserting the data: >SqlException: Cannot insert the value NULL into column 'TenantId', table 'DBContext.dbo.Tenants';但是,当我尝试迁移到 EF Core 时,我在插入数据时收到一条错误消息:>SqlException:无法将值 NULL 插入列 'TenantId',表 'DBContext.dbo.Tenants'; column does not allow nulls.
列不允许空值。 INSERT fails.
插入失败。 The statement has been terminated.
该语句已终止。
Here's my new code:这是我的新代码:
[Key, Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public Guid TenantId { get; set; }
Fluent:流畅:
base.OnModelCreating(builder);
builder.Entity<Tenant>()
.HasIndex(t => t.TenantId)
.IsUnique();
builder.Entity<Tenant>()
.Property(t => t.TenantId)
.ValueGeneratedOnAdd();
This is inserted by using:这是通过使用插入的:
_context.Tenants.Add(tenant);
await _context.SaveChangesAsync();
Is this something that is not supported by EF Core and requires a workaround?这是 EF Core 不支持并需要解决方法的东西吗?
On your new code you don't have the [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
annotation.在您的新代码中,您没有
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
注释。 Your code should be:你的代码应该是:
[Key, Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid TenantId { get; set; }
I think the reason why you are getting the Null is because you are supposed to instantiate the value of the Guid.我认为您获得 Null 的原因是因为您应该实例化 Guid 的值。 something like
就像是
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid TenantId { get; set; } = Guid.NewGuid();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.