EF Core模型建立惯例 [英] EF Core model building conventions

查看:69
本文介绍了EF Core模型建立惯例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In EF6 it was possible to define conventions based on property types during model building, like so...

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

此方法也可以用于设置默认的字符串长度/零度,等等.

This approach could also be used to set default string length/null-ness, and so forth.

我仔细研究了EF核心模型和相关类型,找不到通过迁移构建器制定的方法或没有导致迁移构建器完全拒绝该模型的方式应用等效约定的方法.这是完全令人沮丧的,而且似乎是退步的.

I have looked through the EF Core Model and associated types and can find no way of applying an equivalent convention in a way that is either enacted by the migration builder, or that does not cause migration builder to reject the model altogether. This is entirely frustrating and seems regressive.

更新

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

Adding the following to the OnModelCreating event...

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

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

...produces the following message on 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.

推荐答案

这可以完成工作,但是非常不雅致.

This does the job, but it's pretty inelegant.

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

这篇关于EF Core模型建立惯例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆