Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Represent a single-rowed table in EF?

I have a configuration table in my database and it contains exactly one row.

ConfirmedScheduleColor | OverlappedScheduleColor | ColN

Currently, I'm retrieving the configuration like this:

var db = new SchedulingDbContext();
var config = db.Configurations.FirstOrDefault();

It's currently working fine and I can access my configurations and all. The thing is, the code looks awkward since I'm accessing the Configurations DbSet as if it contains many records (FirstOrDefault()); although actually, it contains only one record. I want to access my configurations like I'm accessing a static object. How to do that in EF?

like image 744
dpp Avatar asked Dec 02 '22 21:12

dpp


1 Answers

You could simply add a property to your DbContext that returns Configurations.FirstOrDefault() and privatize the DbSet:

public class SchedulingDbContext : DbContext
{
    private DbSet<Configuration> Configurations { get; set; }

    public Configuration Configuration
    {
        get
        {
            return Configurations.FirstOrDefault();
        }
    }
}
like image 173
Moho Avatar answered Jan 17 '23 07:01

Moho