我有一个ApplicationUser
和一个Group
:
public class ApplicationUser : IdentityUser
{
public int? GroupId { get; set; }
public Group Group { get; set; }
// ... some more properties
}
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
public string GroupAdminId { get; set; }
public ApplicationUser GroupAdmin { get; set; }
public List<ApplicationUser> GroupUsers { get; set; }
}
这个想法是,一个组有一个管理员用户和许多普通用户。另外,ApplicationUser
只能是Group
的成员,可以是管理员或普通用户。
ApplicationUser
的PK的类型为string
(向导)。
我正在尝试在OnModelCreating()
中定义关系,但是我做的不正确:
modelBuilder.Entity<Group>()
.HasOne(a => a.GroupAdmin)
.WithOne(g => g.Group)
.HasForeignKey(a => a.GroupAdminId);
.HasForeignKey(a => a.GroupAdminId)
导致此错误:
错误CS1660无法将lambda表达式转换为类型'string',因为它不是委托类型
modelBuilder.Entity<Group>()
.HasMany(u => u.GroupUsers)
.WithOne(g => g.Group);
GroupUsers
的配置没有显示任何错误,但是由于GroupAdmin
部分不起作用,所以我没有对其进行测试。
我不太了解这些东西,但是我读了一点here,并做了一些实验,这似乎可行:
我修改了ApplicationUser
模型,以区分与Group
的管理员和用户关系:
public class ApplicationUser : IdentityUser
{
public int? AdminInGroupId { get; set; }
public int? UserInGroupId { get; set; }
public Group AdminInGroup { get; set; }
public Group UserInGroup { get; set; }
}
OnModelCreating()
配置:
modelBuilder.Entity<Group>()
.HasOne(a => a.GroupAdmin)
.WithOne(g => g.AdminInGroup)
.HasForeignKey<ApplicationUser>(a => a.AdminInGroupId);
modelBuilder.Entity<Group>()
.HasMany(u => u.GroupUsers)
.WithOne(g => g.UserInGroup)
.OnDelete(DeleteBehavior.NoAction);