[英]Entity Framework Core Many-to-Many relationship with IdentityUser
I am looking a way to bind the default IdentityUser
with a custom class but I am getting this error: 我正在寻找一种方法来将默认的IdentityUser
与自定义类绑定,但出现此错误:
Column names in each table must be unique. 每个表中的列名必须唯一。 Column name 'AppUserId' in table 'HMTUser' is specified more than once. 表“ HMTUser”中的列名“ AppUserId”已多次指定。
AppUser
class: AppUser
类:
public class AppUser : IdentityUser
{
public string FName { get; set; }
public string LName { get; set; }
public List<HMTUser> HMTUsers { get; set; }
}
HMT class: HMT类别:
public class HMT
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int HID { get; set; }
public string Name { get; set; }
public List<HMTUser> HMTUsers { get; set; }
}
HUser class: HUser类:
public class HMTUser
{
public int AppUserID { get; set; }
public AppUser AppUser { get; set; }
public int HHID { get; set; }
public HMT HMT { get; set; }
}
and have defined the OnModelCreating with 并定义了OnModelCreating
modelBuilder.Entity<HMTUser>()
.HasKey(s=> new { s.HHID , s.AppUserID });
I am uncertain on int
part as AppUser
is derived from IdentityUser
and id
is varchar
, will this be the case? 我不确定int
部分,因为AppUser
是从IdentityUser
派生的,而id
是varchar
,会是这种情况吗?
UPDATE UPDATE
Changing the int to string did the job but ef core was asking for a PK in HMTUser entity so made a new one using 将int更改为string可以完成工作,但是ef core要求在HMTUser实体中请求PK,因此使用
[Key] [键]
It works but it also create a new table name 它可以工作,但也可以创建一个新的表名
'AppUser' 'APPUSER'
which is not used to store user data, user data is still saved in default 它不用于存储用户数据,默认情况下仍保存用户数据
'AspNetUsers' 'AspNetUsers'
table. 表。
I have tested your code and I think one solution is to change the type of the AppUserId
from int
to string
. 我已经测试了您的代码,并且我认为一种解决方案是将AppUserId
的类型从int
更改为string
。 With this change everything works fine. 通过此更改,一切正常。 The code generated after migration: 迁移后生成的代码:
migrationBuilder.CreateTable(
name: "HMTUsers",
columns: table => new
{
AppUserId = table.Column<string>(nullable: false),
HHID = table.Column<int>(nullable: false),
HMTHID = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_HMTUsers", x => new { x.HHID, x.AppUserId });
table.ForeignKey(
name: "FK_HMTUsers_AppUsers_AppUserId",
column: x => x.AppUserId,
principalTable: "AppUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_HMTUsers_HTMs_HMTHID",
column: x => x.HMTHID,
principalTable: "HTMs",
principalColumn: "HID",
onDelete: ReferentialAction.Restrict);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.