Rug*_*SR9 4 c# asp.net-mvc asp.net-identity entity-framework-core
我一直在搜索过去三个小时,试图弄清发生了什么,最后不得不分解并发布问题。
我试图将WithRequired()/ HasRequired()添加到ApplicationUser的模型构建器中,但是它告诉我未定义。
我是在这里只是完全无知,还是在.Net Core / EF Core框架中改变了这一点?
应用用户:
public class ApplicationUser : IdentityUser
{
[Required]
[StringLength(100)]
public string Name { get; set; }
public ICollection<Following> Followers { get; set; }
public ICollection<Following> Followees { get; set; }
public ApplicationUser()
{
Followers = new Collection<Following>();
Followees = new Collection<Following>();
}
}
Run Code Online (Sandbox Code Playgroud)
following.cs:
public class Following
{
[Key]
[Column(Order = 1)]
public string FollowerId { get; set; }
[Key]
[Column(Order = 2)]
public string FolloweeId { get; set; }
public ApplicationUser Follower { get; set; }
public ApplicationUser Followee { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
ApplicationDbContext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Gig> Gigs { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Attendance> Attendances { get; set; }
public DbSet<Following> Followings { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
builder.Entity<Attendance>()
.HasKey(c => new { c.GigId, c.AttendeeId });
builder.Entity<ApplicationUser>()
.HasMany(u => u.Followers);
builder.Entity<ApplicationUser>()
.HasMany(u => u.Followees);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用
builder.Entity<ApplicationUser>()
.HasMany(u => u.Followers).WithOne(tr => tr.Follower).IsRequired()
Run Code Online (Sandbox Code Playgroud)
装的
builder.Entity<ApplicationUser>()
.HasMany(u => u.Followers).WithRequired(tr => tr.Follower)
Run Code Online (Sandbox Code Playgroud)
你需要这样写才能得到WithRequired()(根据你的Following班级)
builder.Entity<Following>().HasRequired(u=>u.Follower).WithMany(u=>u.Followers);
Run Code Online (Sandbox Code Playgroud)
请重写实体以获得正确的输出。
IE
public class ApplicationUser : IdentityUser{
[Required]
[StringLength(100)]
public string Name { get; set; }
public Following Follower { get; set; }
}
public class Following{
[Key]
[Column(Order = 1)]
public string FollowerId { get; set; }
[Key]
[Column(Order = 2)]
public string FolloweeId { get; set; }
public ICollection<ApplicationUser> Followers { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
那么OnModelCreating就会是
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<ApplicationUser>()
.HasRequired(u=>u.Follower)
.HasMany(u => u.Followers);
}
Run Code Online (Sandbox Code Playgroud)