【发布时间】:2015-10-24 13:33:55
【问题描述】:
我使用的是开箱即用的ApplicationUser,但还有一些额外的属性:
public class ApplicationUser : IdentityUser, IPayCaddyEntity
{
...
// TODO Figure out how to config.
public string FullName { get; set; }
public string CellNumber { get; set; }
}
然后对于“映射”,我为几乎所有实体的EntityConfig 类使用以下基类:
abstract class EntityConfigBase<TEntity>: EntityTypeConfiguration<TEntity> where TEntity: class, IPayCaddyEntity
{
protected EntityConfigBase()
{
HasKey(e => e.Id);
}
}
其中IPayCaddyEntity 仅确保所有实体的Id 属性:
public interface IPayCaddyEntity
{
string Id { get; set; }
}
现在,更接近手头的问题,ApplicationUser 的配置:
class ApplicationUserConfig: EntityConfigBase<ApplicationUser>
{
public ApplicationUserConfig()
{
Property(e => e.FullName).IsRequired().HasMaxLength(MaxNameLength);
Property(e => e.CellNumber).IsRequired().HasMaxLength(20);
}
}
我还在使用开箱即用的IdentityDbContext,以及其他应用表:
public class PayCaddyDbContext : IdentityDbContext<ApplicationUser>
{
...
public DbSet<AccountPayment> AccountPayments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Configurations.Add(new ApplicationUserConfig());
modelBuilder.Configurations.Add(new AccountPaymentConfig());
base.OnModelCreating(modelBuilder);
}
}
当添加 ApplicationUserConfig 被注释掉时,一切正常,但它可以正常运行,当我尝试登录应用程序时,即当它尝试访问用户表时,我收到以下错误:
关键组件“Id”不是类型上的声明属性 '应用用户'
在我自己的代码之前调用base.OnModelCreating(modelBuilder) 没有明显的区别。
现在它是IdentityUser<TKey, TLogin, TRole, TClaim> 上的声明属性,ApplicationUser 最终派生自该属性。通常继承不是问题,因为我所有的其他实体也都从一个公共基类中获得了它们的 Id 属性:
public abstract class BaseEntity : IBaseEntity
{
public string Id { get; set; }
}
public class AccountPayment : BaseEntity
{
...
}
我没有得到任何其他实体的错误(为简洁起见,我在这里删除了很多),我能做出的最接近的猜测是ApplicationUser 仅来自接口IBaseEntity,而不是来自BaseEntity ,它通常提供Id 属性。
这是问题的原因吗,或者是什么,除了直接在OnModelCreating 中配置我自己的ApplicationUser 属性外,我能做些什么来解决它吗?
【问题讨论】:
-
你有没有试过调用 base.OnModelCreating(modelBuilder);第一的?我知道这应该没什么区别,但是 Identity/EF 耦合让我很伤心。
-
我想我最初拥有它并且不得不移动它,但会尝试再次交换,谢谢。
-
不,@SteveGreene,我现在已经尝试过了,似乎没什么区别。
-
调用 base.OnModelCreating(modelBuilder) 完全没有任何作用。根据the documentation,
The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down. -
@TimCooke 它只在
DbContext和派生类中什么都不做。它在我的上下文中做了很多,源自IdentityDbContext<ApplicationUser>。
标签: c# entity-framework ef-code-first entity-framework-6