C
C#9mo ago
RV

Inheritance Cast

Please help me c#, level intermediate Problem Code:
namespace InheritanceProblem
{
public class IdentityUser {
[Key]
public required string Id { get; set; }

}
public class AppUser : IdentityUser {
public required string Name { get; set; }
}

public class IdentityDbContext<TUser> : DbContext where TUser : IdentityUser
{
public IdentityDbContext(DbContextOptions options) : base(options) { }
public DbSet<TUser> Users { get; set;}
}

public class AppDbContext : IdentityDbContext<AppUser>
{
public AppDbContext(DbContextOptions options) : base(options) { }
}

public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
DbContextOptionsBuilder optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer("");
return new AppDbContext(optionsBuilder.Options);
}
}

public class SomeClass
{
public IdentityUser FindFirstUser(IdentityDbContext<IdentityUser> dbContext) => dbContext.Users.First();
}

public class Main
{
public Main()
{
SomeClass someClass = new SomeClass();
AppDbContext context = new AppDbContextFactory().CreateDbContext(null);
someClass.FindFirstUser(context);
}
}
}
namespace InheritanceProblem
{
public class IdentityUser {
[Key]
public required string Id { get; set; }

}
public class AppUser : IdentityUser {
public required string Name { get; set; }
}

public class IdentityDbContext<TUser> : DbContext where TUser : IdentityUser
{
public IdentityDbContext(DbContextOptions options) : base(options) { }
public DbSet<TUser> Users { get; set;}
}

public class AppDbContext : IdentityDbContext<AppUser>
{
public AppDbContext(DbContextOptions options) : base(options) { }
}

public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
DbContextOptionsBuilder optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer("");
return new AppDbContext(optionsBuilder.Options);
}
}

public class SomeClass
{
public IdentityUser FindFirstUser(IdentityDbContext<IdentityUser> dbContext) => dbContext.Users.First();
}

public class Main
{
public Main()
{
SomeClass someClass = new SomeClass();
AppDbContext context = new AppDbContextFactory().CreateDbContext(null);
someClass.FindFirstUser(context);
}
}
}
How can I convert from AppDbContext to IdentityDbContext<IdentityUser> ??
No description
4 Replies
maxmahem
maxmahem9mo ago
you don't. You can't case from parent to derived. Call the derived ctor.
viceroypenguin
viceroypenguin9mo ago
the generic argument is not replacable in FindFirstUser. use FindFirstUser(IdentityDbContext<AppUser> dbContext) instead, and it'll work
RV
RVOP9mo ago
I can't change it to AppUser because it's from different library where there is no AppUser class. Thanks I found solution by myself.
No description
viceroypenguin
viceroypenguin9mo ago
that also works, yeah
Want results from more Discord servers?
Add your server