Microsoft.EntityFramework.core.sqlite返回空值

时间:2018-07-03 07:39:25

标签: c# xamarin xamarin.android entity-framework-core-2.1

我正在.netstandard 2.0上的Xamarin pcl项目上工作,并使用 Microsoft.EntityFramework.core.sqlite

DatabaseContext

public class DatabaseContext: DbContext
{
    private readonly string _databasePath;

    // Hotworks related tables
    public DbSet<A> a { get; set; }
    public DbSet<B> b { get; set; }
    public DbSet<C> c { get; set; }
    public DbSet<D> d { get; set; }

    public DatabaseContext(string databasePath)
    {
        _databasePath = databasePath;
        this.Database.EnsureCreated();
    }

    public override int SaveChanges()
    {
        AddTimestamps();
        return base.SaveChanges();
    }

    public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        AddTimestamps();
        return (await base.SaveChangesAsync(true, cancellationToken));
    }

    private void AddTimestamps()
    {
        var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));


        foreach (var entity in entities)
        {
            var now = DateTime.UtcNow; // current datetime

            if (entity.State == EntityState.Added)
            {
                ((BaseEntity)entity.Entity).CreatedAt = now;
            }
        ((BaseEntity)entity.Entity).UpdatedAt = now;              
        }
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {           
        optionsBuilder.UseSqlite($"Filename={_databasePath}");
    }
}

模型类

 public class A:BaseEntity
{
    public int id { get; set; }
    public B b { get; set; }
    public C c { get; set; }
    public virtual ICollection<D> d { get; set; }= new HashSet<D>();
    public string Name { get; set; }       
}

public abstract class BaseEntity
{
    public DateTime? CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }
}

当我向数据库中添加类“ A”的对象时:

var aIns = await _databaseContext.A.AddAsync(a);          
await _databaseContext.SaveChangesAsync();
var isAdded = sIns.State == EntityState.Added;

我把我的收藏夹当作假的。但是,正如我通过获取所有A的列表(但A实例中的所有其他元素,例如 B,C和D 列表)都为空所确认的那样,它已保存在数据库中。我还确认,在保存A之前,我已将B,C和D的各个实例分别保存到各自的表中。

我在这里处理任何错误,还有更多要做的事情吗? 提前致谢。

1 个答案:

答案 0 :(得分:0)

您输入的变更跟踪信息有误。

您的测试应该看起来像这样:

var isAdded = _databaseContext.A.Any(arow => arow.id == a.id);

因为您无论如何都不应该关注变更跟踪的内部。您应该注意保存的数据以后是否可以加载。