gpt4 book ai didi

asp.net - 如何将 ASP.Net Identity User Email 属性引用为外键

转载 作者:行者123 更新时间:2023-12-04 18:07:22 29 4
gpt4 key购买 nike

尝试将 ASP.Net 身份用户的电子邮件属性引用为外键,但不断收到错误消息

使用 MVC6、EF7

我有一个 AppAccount,它是主要模型,ApplicationUser: IdentityUser 是从属模型。

我正在尝试将 ApplicationUserEmail 属性设置为 AppAccount 模型的外键

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

}

“查看”IdentityUser 的定义告诉我电子邮件属性是字符串类型...

public class IdentityUser<TKey> where TKey : IEquatable<TKey>
{
...
//
// Summary:
// Gets or sets the email address for this user.
public virtual string Email { get; set; }
...
}

我已将 AppAccount 模型的 PK 设置为字符串,并将 ApplicationUserEmail 属性设置为备用键,然后设置一个使用流畅的 API 的一对一关系...

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.

我尝试手动将 AppAccountIDEmail 属性的最大长度设置为相同的限制

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

尝试将 ApplicationUser 类中的 Email 属性覆盖为

public override string Email {get ; set ;}

我尝试将 AppAccount 模型的 AppAccountID 属性设置为 virtual

`public virtual string AppAccountID {get ; set ;}

我认为这可能是服务器问题,但检查数据库时 Email 列类型是 nvarchar,所以我不明白为什么它不能编译?

最佳答案

试试这个模型

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

}

关于asp.net - 如何将 ASP.Net Identity User Email 属性引用为外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40010350/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com