gpt4 book ai didi

c# - 来自基类的索引数据注释的异常

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:13 25 4
gpt4 key购买 nike

我从 ASP.net Core 开始创建我的模型。
我刚刚创建了两个:一个叫做 dto,它将成为我所有数据库模型的基础,看起来像这样:

public abstract class Dto
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Clustered]
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime LastUpdate { set; get; }
}

另一个叫做订阅,它看起来像这样:

public class Subscription:Dto
{
public string Name { get; set; }
public decimal Price { set; get; }
public string MeliApiKey { get; set; }
public int MaxQueries { get; set; }
public int UsedQueries { get; set; }

}

我在 Fluent API 上有以下配置:

modelBuilder.Entity<Dto.Dto>().Property(x => x.CreatedAt).HasDefaultValueSql("SYSUTCDATETIME()");
modelBuilder.Entity<Dto.Dto>().Property(x => x.LastUpdate).HasComputedColumnSql("SYSUTCDATETIME()");

foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
foreach (var prop in entity.GetProperties())
{
var attr = prop.PropertyInfo?.GetCustomAttribute<ClusteredAttribute>(true);
if (attr != null)
{
var index = entity.AddIndex(prop);
index.IsUnique = true;
index.SqlServer().IsClustered = true;
}
}
}

我只添加了 subscription 作为 dbset,因为我不想用 dto 继承 Table Per Hierarchy。

当我运行 add-migration 时,出现以下错误:

"The index {'CreatedAt'} cannot be added to the entity type 'Subscription' because an index on the same properties already exists on entity type 'Dto'"

现在我用谷歌搜索了这个错误,但我在任何地方都看不到如何解决这个问题。

我是否应该删除 dto 类并将相同的属性添加到将代表我的模型的每个对象?

最佳答案

如错误所述,索引已经在基类的属性上定义。检查该属性是否在您当前正在处理的实体的同一类型中声明,类似于:

var propertiesToProcess = entity.GetProperties()
.Where( p => entity.ClrType == p.PropertyInfo.DeclaringType );

关于c# - 来自基类的索引数据注释的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52618337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com