尝试将ASP.Net Identity User的Email属性作为外键引用,但不断收到错误消息
使用MVC6,EF7
我有一个AppAccount
是主要模型,而ApplicationUser: IdentityUser
是相关的。
我试图将Email
的{{1}}属性设置为ApplicationUser
模型的外键
AppAccount
'偷看' IdentityUser的定义告诉我,Email属性的类型为string ...
public class AppAccount
{
public string AppAccountID { get; set; }
public string AccountType { get; set; }
public DateTime DateCreated { get; set; }
public virtual ApplicationUser AppUser { get; set; }
}
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string Surname { get; set; }
public DateTime DOB { get; set; }
public virtual AppAccount AppAccount { get; set; }
}
我已将public class IdentityUser<TKey> where TKey : IEquatable<TKey>
{
...
//
// Summary:
// Gets or sets the email address for this user.
public virtual string Email { get; set; }
...
}
模型的PK设置为字符串,并将AppAccount
的{{1}}属性设置为备用键,然后使用fluent API设置一对一关系...
Email
当我运行迁移时,它可以正常运行,但是当我尝试更新数据库时,我收到以下错误
ApplicationUser
我尝试手动将builder.Entity<ApplicationUser>(au =>
{
au.HasAlternateKey(u => u.Email);
au.HasAlternateKey(u => u.UserName);
});
builder.Entity<AppAccount>(aa =>
{
aa.HasKey(a => a.AppAccountID);
aa.HasOne(a => a.AppUser)
.WithOne(u => u.AppAccount)
.HasPrincipalKey<ApplicationUser>(u => u.Email); // PK of AppAccount is FK of AppUser
});
和Error Number:1753,State:0,Class:16
Column 'AspNetUsers.Email' is not the same length or scale as
referencing column 'AppAccount.AppAccountID'
in foreign key 'FK_AppAccount_ApplicationUser_AppAccountID'.
Columns participating in a foreign key relationship must
be defined with the same length and scale.
Could not create constraint or index. See previous errors.
属性的最大长度设置为相同的限制
AppAccountID
我已尝试在服务器上将两个属性设置为相同类型...
Email
尝试覆盖builder.Entity<ApplicationUser>(au =>
{
...
au.Property(u => u.Email).HasMaxLength(100);
});
builder.Entity<AppAccount>(aa =>
{
...
aa.Property(a => a.AppAccountID).HasMaxLength(100);
...
});
类中的builder.Entity<ApplicationUser>(au =>
{
...
au.Property(u => u.Email).ForSqlServerHasColumnType("nvarchar(100)");
});
builder.Entity<AppAccount>(aa =>
{
...
aa.Property(a => a.AppAccountID).ForSqlServerHasColumnType("nvarchar(100)");
...
});
属性
Email
我尝试将ApplicationUser
模型的public override string Email {get ; set ;}
属性设置为AppAccountID
AppAccount
我认为这可能是服务器问题,但检查数据库virtual
列类型是nvarchar,所以我不明白它为什么不编译?
答案 0 :(得分:0)
试试这个模型
public class AppAccount
{
public string AppAccountID { get; set; }
public string AccountType { get; set; }
public DateTime DateCreated { get; set; }
[ForeignKey("UserId")
public virtual ApplicationUser AppUser { get; set; }
}
答案 1 :(得分:0)
道歉所有,业余时间
首先我正在编写HasForeignKey
而不是Email
,正如@TetsuyaYamamoto(Thankyou)指出的那样。
其次,在无数次检查数据库后,ApplicationUser
的{{1}}属性类型为NVARCHAR(256)
,因此更新自定义如下所示允许EF成功编译模型。
builder.Entity<AppAccount>(aa =>
{
aa.HasKey(a => a.AppAccountID);
aa.Property(a => a.AppAccountID).ForSqlServerHasColumnType("NVARCHAR(256)");
aa.HasOne(a => a.AppUser)
.WithOne(u => u.AppAccount)
.HasForeignKey<ApplicationUser>(u => u.Email);
});
全部谢谢...这就是为什么你不在早上1点编码