【问题标题】:EF Core model building conventionsEF Core 模型构建约定
【发布时间】:2017-08-25 13:42:50
【问题描述】:

在 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();
}

...在添加迁移时产生以下消息

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.

【问题讨论】:

标签: c# entity-framework asp.net-core entity-framework-core


【解决方案1】:

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

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()");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-27
    • 2021-09-25
    • 2018-05-01
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多