Entity Framework Core single object instead of List

asp.net-core c# design-patterns entity-framework entity-framework-core


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
    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?


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
public IActionResult GetFarms() => Ok(_context.Farms.SingleOrDefault());

Can i call my Farm.GetFarm() => this.farm from DBContext?

1/7/2019 7:32:14 AM

Accepted Answer

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

1/7/2019 7:18:46 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow