我无法将我的存储库插入到我的数据库中。
我的背景:
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对象不会插入我的数据库。
我完全错过了什么吗?
提前致谢。
答案 0 :(得分:5)
您需要等待appRepos.Add,因为它是异步方法。否则,程序将在执行异步方法之前终止。
await appRepos.Add(test);