Just started using ASP.net, moved from JAVA. Trying to auto-generate controller for project. While I managed to do so in tutorial on official web-site, found a problem to make it work on my "test" project. Problem encountered when I put some collection inside Entity, without this collection it works fine.
The question is how to make it work? I assume that the problem is somewhere in connection between two DBs (which is one (User)-to-many(Links).
This is User model:
public class UserItem
{
[Key]
public long UserId { get; set; }
[Required]
[MinLength(3, ErrorMessage = "Min 3 char")]
[MaxLength(20)]
public string? Name { get; set; }
[Required]
[MinLength(6, ErrorMessage = "Min 6 char"), MaxLength(20)]
public required string Password { get; set; } // todo: private set;
// [ForeignKey("Links")]
// [ConcurrencyCheck]
public ICollection<LinkItem> Links { get; set; }
public UserItem()
{
Links = new List<LinkItem>();
}
}
This is Link model:
public class LinkItem
{
[Key]
public long UserId { get; set; }
[ForeignKey("UserId")]
public UserItem? UserItem { get; set; }
public string? Link { get; set; }
}
This is DbContext:
public class UserLinksDb : DbContext
{
public UserLinksDb(DbContextOptions<UserLinksDb> options) : base(options) { }
public DbSet<UserItem> UserItems { get; set; } = null!;
public DbSet<LinkItem> LinkItems { get; set; } = null!;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LinkItem>().HasKey(k => k.UserId);
modelBuilder.Entity<LinkItem>( e =>
{
e.HasKey(k => k.UserId);
e.HasOne(k => k.UserItem)
.WithMany(k => k.Links)
.HasForeignKey(k => k.UserId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
}
}
This is how I connect to in-memory DB :
builder.Services.AddDbContext<UserLinksDb>(option => option.UseInMemoryDatabase("LinksList"));
And this is how I try to generate controller:
dotnet aspnet-codegenerator controller -name LinksController -async -api -m UserItem -dc UserLinksDb -outDir Controllers
When I try to execute code-generator command in terminal, I get this error: Could not get the reflection type for DbContext : UserLinksDb