Thisen
Thisen

Reputation: 183

Using DbContext.Set<T>.Add() Wont add to Database

I'm having trouble getting my repository to insert into my database.

My Context:

public class Context : DbContext
{
    public Context() : base("MyDatabase")
    {

    }

    public DbSet<Appartment> Appartments { get; set; }
    public DbSet<Sensor> Sensors { get; set; }
    public DbSet<Measurement> Measurements { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Measurement>().HasKey(m => new {m.AppartmentId, m.SensorId});

        modelBuilder.Entity<Measurement>()
            .HasRequired(m => m.Appartment);

        modelBuilder.Entity<Measurement>()
            .HasRequired(m => m.Sensor);
    }
}

My entity:

public class Appartment
{
    public int AppartmentId { get; set; }
    public int Floor { get; set; }
    public int Number { get; set; }
    public double Size { get; set; }

    public ICollection<Measurement> Measurements { get; set; }

    public Appartment()
    {

    }

    public Appartment(int floor, int number, int size)
    {
        Floor = floor;
        Number = number;
        Size = size;
    }
}

My Repository:

public class Repository<T> where T : class
{
    private Context _context;

    public Repository(Context context)
    {
        _context = context;
    }

    public async Task<int> Add(T t)
    {
        _context.Set<T>().Add(t);
        return await _context.SaveChangesAsync();
    }

My test:

class Program
{
    static void Main(string[] args)
    {
        var context = new Context();
        var appRepos = new Repository<Appartment>(context);

        var test = new Appartment(1,1,1);
        appRepos.Add(test);
}

Using this, the Appartment object isn't inserted into my database.

Am I missing something completely?

Thanks in advance.

Upvotes: 2

Views: 1643

Answers (1)

Bill Cheng
Bill Cheng

Reputation: 956

You will need to await appRepos.Add since it is an async method. Otherwise, your program will terminate before the async method get executed.

await appRepos.Add(test);

Upvotes: 5

Related Questions