【问题标题】:Entity framework migrations throws exception when using extension method for fluent API使用 Fluent API 的扩展方法时,实体框架迁移引发异常
【发布时间】:2017-06-06 14:27:22
【问题描述】:

我正在使用实体框架 6,代码优先和 Fluent-API。

我有以下扩展方法来设置我的实体的主键:

public static class ConfigurationExtensions
{
    public static void HasPrimaryKey<TEntityType>(this EntityTypeConfiguration<TEntityType> configuration)
        where TEntityType : class, IEntity
    {
        configuration
            .HasKey(m => m.Id)
            .Property(t => t.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

每个代码优先实体都实现以下简单接口:

public interface IEntity
{
    int Id { get; }
}

现在假设我有以下实体:

public class MyEntity : IEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我在 DbContext 中使用 Fluent-API 进行配置

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new MyEntityConfiguration());
}

实体的配置类:

public class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
{
    public MyEntityConfiguration()
    {
        this.HasPrimaryKey()
    }
}

奇怪的是,当我在 包管理器控制台中执行 Add-Migration 时我得到以下异常:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: The property 'Id' cannot be used as a key property on the entity 'MyEntity' because the property type is not a valid key type. Only scalar types, string and byte[] are supported key types.
   at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Key(PropertyInfo propertyInfo, Nullable`1 overridableConfigurationParts)
   at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Key(IEnumerable`1 keyProperties)
   at System.Data.Entity.ModelConfiguration.EntityTypeConfiguration`1.HasKey[TKey](Expression`1 keyExpression)
   at ConfigurationExtensions.HasPrimaryKey[TEntityType](EntityTypeConfiguration`1 configuration) in C:\path\ConfigurationExtensions.cs

这很奇怪,因为当我将扩展方法中的代码重构回构造函数时,如下所示:

public class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
{
    public MyEntityConfiguration()
    {
        HasKey(m => m.Id)
        .Property(t => t.Id)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

然后,框架不会抛出异常,并且一切都按预期工作。为什么?框架错误?

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    异常消息具有误导性。实际问题相当琐碎。 EF 仅支持具有属性设置器的属性。

    由于通用扩展方法中的表达式m =&gt; m.Id 绑定到IEntity 接口的Id 属性,该接口没有setter(与实现类相反),EF 不认为它是一个有效的属性并且引发异常并带有关于属性类型的误导性消息。

    要修复它,只需在接口内为Id 属性定义setter:

    public interface IEntity
    {
        int Id { get; set; }
    }
    

    也可以通过使用 Expression 类方法手动构建 lambda 表达式来解决,但我认为修改接口更容易:) 但这里是为了完整性,以防你不想破坏你的接口设计:

    public static class ConfigurationExtensions
    {
        public static void HasPrimaryKey<TEntityType>(this EntityTypeConfiguration<TEntityType> configuration)
            where TEntityType : class, IEntity
        {
            var parameter = Expression.Parameter(typeof(TEntityType), "m");
            var keyProperty = Expression.Lambda<Func<TEntityType, int>>(Expression.Property(parameter, nameof(IEntity.Id)), parameter);
            configuration
                .HasKey(keyProperty)
                .Property(keyProperty)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        }
    }
    

    【讨论】:

    • 我接受这个答案,因为它阐明了 Entity Framework 抛出异常的原因。显然IEntity 接口在应用程序的架构和设计中定义了一个契约,因此更改它会破坏该架构的初始设计。我宁愿有一个SOLID 设计,而不是一个通用的扩展方法,其唯一目的是充当帮助方法,使代码多一点DRY。
    • 还有一件有趣的事情需要注意的是,像微软这样的公司正在抛出这样一个误导性的异常,从而违反了他们自己在 Framework Design Guidelines 上的异常规则/指南。
    猜你喜欢
    • 1970-01-01
    • 2020-04-13
    • 2017-08-09
    • 1970-01-01
    • 2012-03-17
    • 2017-03-12
    • 2016-06-18
    • 2018-09-13
    • 1970-01-01
    相关资源
    最近更新 更多