gpt4 book ai didi

c# - EF Core 模型构建约定

转载 作者:太空宇宙 更新时间:2023-11-03 12:24:15 24 4
gpt4 key购买 nike

在 EF6 中,可以在模型构建期间根据属性类型定义约定,就像这样...

public interface IEntity
{
Guid Id { get; }
}

public class MyEntity : IEntity
{
public Guid Id { get; set; }
}

public class MyDbContext : DbContext
{
public override void OnModelCreating(DbModelBuilder builder)
{
builder
.Properties<Guid>()
.Where(x => x.Name == nameof(IEntity.Id)
.Configure(a=>a.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity));
}
}

此方法也可用于设置默认字符串长度/空性等。

我查看了 EF Core 模型和相关类型,但找不到以迁移构建器制定的方式或不会导致迁移构建器完全拒绝模型的方式应用等效约定的方法。这完全令人沮丧,而且似乎倒退了。

更新

将以下内容添加到 OnModelCreating 事件中...

foreach (var pb in builder.Model
.GetEntityTypes()
.Where(x=>typeof(IEntity).IsAssignableFrom(x.ClrType))
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(Guid) && p.Name == nameof(IEntity.Id))
.Select(p => builder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name)))
{
pb.UseSqlServerIdentityColumn();
}

...在 Add-Migration 上生成以下消息

Identity value generation cannot be used for the property 'Id' on entity type 'Tenant' because the property type is 'Guid'. Identity value generation can only be used with signed integer properties.

最佳答案

这样可以完成工作,但它很不优雅。

foreach (PropertyBuilder pb in builder.Model
.GetEntityTypes()
.Where(x=>typeof(IEntity).IsAssignableFrom(x.ClrType))
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(Guid) && p.Name == nameof(IEntity.Id))
.Select(p => builder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name)))
{
pb.ValueGeneratedOnAdd().HasDefaultValueSql("newsequentialid()");
}

关于c# - EF Core 模型构建约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45882787/

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