使用 DbContext.Set<T>.Add() 不会添加到数据库

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

我无法将我的存储库插入到我的数据库中。

我的背景:

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);
    }
}

我的实体:

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;
    }
}

我的存储库:

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();
    }

我的测试:

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);
}

使用此方法,Appartment 对象不会插入到我的数据库中。

我是不是完全漏掉了什么?

提前致谢。

您需要等待 appRepos.Add,因为它是一个异步方法。否则,您的程序将在异步方法执行之前终止。

await appRepos.Add(test);