I have a question. Is it possible to force Entity Framework to make one instance of class instead of (for example) IEnumerable
?
In my database, i want to have only one Farm
instead of Farms
. My Farm
have all other List in it that i mentioned in my DBContext:
public class FarmDbContext : DbContext
{
public FarmDbContext(DbContextOptions<FarmDbContext> options) : base(options) { }
public DbSet<Farm> Farms { get; set; } //i want to have one instance of farm
public DbSet<Machine> Machines { get; set; }
public DbSet<Stable> Stables { get; set; }
public DbSet<Worker> Workers { get; set; }
public DbSet<Cultivation> Cultivations { get; set; }
}
And my Farm class, that is a Singleton (class with private constructor only with GetInstance()
method):
public class Farm
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Stable> Stables { get; set; }
public virtual List<Machine> Machines { get; set; }
public virtual List<Worker> Workers { get; set; }
public virtual List<Cultivation> Cultivations { get; set; }
public Farm GetFarm() => farm;
private Farm farm;
private Farm() { }
}
So how to make one Farm
in whole database in Code First EntityFramework Core?
EDIT
Maybe i wont 100% accurate with my question.
How to get single instance of Farm every time, i call a context? For example, i have a GET
function:
private readonly FarmDbContext _context;
public FarmController(FarmDbContext context) => _context = context;
// GET: api/Farm
[HttpGet]
public IActionResult GetFarms() => Ok(_context.Farms.SingleOrDefault());
Can i call my Farm.GetFarm() => this.farm
from DBContext
?
Maybe you need to level-up your hierarchy thinking by one, as you have one database, want one farm, make the database the farm and everything inside the database the properties of the single farm.. thus essentially when you write dbContext.Stables.Where... the dbContext IS the farm, the stables are only ever the stables of that one farm. If you want to make another farm, make another database
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