我在Startup.cs文件上指定我在实体项目中创建的上下文类以及为connectionString创建的connectionString数据。但是为什么我会收到此错误?
错误消息: 严重性代码说明项目文件行抑制状态 错误CS0311的类型 'Microsoft.ApplicationInsights.Extensibility.Implementation.UserContext' 不能在通用类型中用作类型参数“ TContext”,或 方法 'EntityFrameworkServiceCollectionExtensions.AddDbContext(IServiceCollection, 操作,ServiceLifetime,ServiceLifetime)”。 没有来自的隐式引用转换 'Microsoft.ApplicationInsights.Extensibility.Implementation.UserContext' 至 'Microsoft.EntityFrameworkCore.DbContext'。 EntityFramework2 C:\ Users \ xsamu \ source \ repos \ EntityFramework2 \ EntityFramework2 \ Startup.cs 29有效
启动类:
namespace EntityFramework2
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<UserContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
实体配置:
namespace EntityFramework2
{
public class EntityConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasOne<Department>(navigationExpression: s => s.Name)
.WithOne(sa => sa.User)
.HasForeignKey<Department>(sa => sa.DepartmentId);
builder.HasOne<Title>(navigationExpression: s => s.TitleCode)
.WithOne(sa => sa.User)
.HasForeignKey<Title>(sa => sa.TitleId);
builder.HasOne<Position>(navigationExpression: s => s.PositionCode)
.WithOne(sa => sa.User)
.HasForeignKey<Position>(sa => sa.PositionId);
}
}
}
答案 0 :(得分:1)
没有从“ Microsoft.ApplicationInsights.Extensibility.Implementation.UserContext”到“ Microsoft.EntityFrameworkCore.DbContext”的隐式引用转换。
该消息告诉您,您的UserContext
类不是从DbContext
继承的,这是强制性的。
它看起来应该像这样:
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
}
有关更多信息,请参见EF Core Tutorial和Configuring a DbContext。
答案 1 :(得分:0)
您的UserContext
是否继承DbContext
类?
答案 2 :(得分:0)
只需让您的上下文 UserContext
继承自 DbContext
类,如下面的代码,您就可以开始了:
public class UserContext : DbContext
{
public UserContext (DbContextOptions<UserContext > options)
: base(options)
{ }
public DbSet<User> Users{ get; set; }
}