字符串作为外键-无法将lambda表达式转换为'string'类型,因为它不是委托类型

问题描述 投票:0回答:1

我有一个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部分不起作用,所以我没有对其进行测试。

c# asp.net-core entity-framework-core ef-code-first relational-database
1个回答
0
投票

我不太了解这些东西,但是我读了一点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);
© www.soinside.com 2019 - 2024. All rights reserved.