I have ConsoleApplication on .NET Core and also i added my DbContext to dependencies, but howewer i have an error:
Unable to create an object of type 'MyContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
i've added: var context = host.Services.GetRequiredService<MyContext>();
Also i've added private readonly DbContextOptions<MyContext> _opts;
in my Post Class:
using (MyContext db = new MyContext(_opts))
{
db.Posts.Add(postData);
db.SaveChanges();
}
This how i added service:
.ConfigureServices((context, services) =>
{
services.Configure<DataOptions>(opts =>
context.Configuration.GetSection(nameof(DataOptions)).Bind(opts));
services.AddDbContext<MyContext>((provider, builder) =>
builder.UseSqlite(provider.GetRequiredService<IOptions<DataOptions>>().Value.ConnectionString));
And this is my Context:
public sealed class MyContext : DbContext
{
private readonly DbContextOptions<MyContext> _options;
public DbSet<PostData> Posts { get; set; }
public DbSet<VoteData> Votes { get; set; }
public MyContext(DbContextOptions<MyContext> options) : base(options)
{
_options = options;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlite("ConnectionString");
}
}
}
I tried add-migration and has this error
What i do wrong?
Delete your Migrations folder. Create a new migration and generate a SQL script for it. In your database, delete all rows from the migrations history table. Insert a single row into the migrations history, to record that the first migration has already been applied, since your tables are already there.
By default, the migrations assembly is the assembly containing the DbContext. Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project."
A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.
I Resolved this by just adding a plain constructor to my Context
public class DataContext : DbContext
{
public DataContext()
{
}
public DataContext(DbContextOptions options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (!options.IsConfigured)
{
options.UseSqlServer("A FALLBACK CONNECTION STRING");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With