Answer the question
In order to leave comments, you need to log in
How to pass context to controller?
There is a book model, a repository and a bdcontext. how to work with the controller through the repository?
book:
public class book
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string description { get; set; }
public int count { get; set; }
public string PhotoPath { get; set; }
public Genre? genres { get; set; }
}
interface IBookView<T> where T : class
{
IEnumerable<T> GetBooksList();
book objectBook(int bookid);
void Add(T item);
void delete(int id);
void update(T item);
void Save();
}
public class BooksContext : DbContext
{
public DbSet<book> Books { get; set; }
//public BooksContext()
//{
// Database.EnsureCreated();
//}
public BooksContext(DbContextOptions<BooksContext> options)
: base(options)
{
Database.EnsureCreated();
}
}
public class BookRepository : IBookView<book>
{
private readonly BooksContext db;
public BookRepository(BooksContext context)
{
db =context;
}
public IEnumerable<book> GetBooksList()
{
return db.Books;
}
public book objectBook(int bookid)
{
return db.Books.Find(bookid);
}
public void Add(book books)
{
db.Books.Add(books);
}
public void update(book books)
{
db.Entry(books).State = EntityState.Modified;
}
public void delete(int id)
{
book books = db.Books.Find(id);
if (books != null)
db.Books.Remove(books);
}
public void Save()
{
db.SaveChanges();
}
}
Answer the question
In order to leave comments, you need to log in
startup.cs
public void ConfigureServices(IServiceCollection services)
{
var con = _configuration.GetConnectionString("telemetry");
services.AddDbContext<TelemetryContext>(options => options.UseSqlServer(con));
}
[ApiController]
[Route("api/[controller]")]
public class TelemetryController : ControllerBase
{
private const int Interval = 15;
private readonly TelemetryContext _ctx;
public TelemetryController(TelemetryContext context)
{
_ctx = context;
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Post(TelemetryModel model)
{
if (ModelState.IsValid)
{
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question