如何在无密钥内存的情况下对EF Core 3视图进行单元测试? [英] How to unit test EF core 3 view with no key in-memory?

查看:54
本文介绍了如何在无密钥内存的情况下对EF Core 3视图进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF Core 3,并编写了一些单元测试,但似乎无法为视图设置测试数据.

I'm playing around with EF Core 3 and writing some unit tests and don't seem to be able to setup test data for a view.

当我尝试保存时,出现错误:

When I'm trying to save, I get the error:

因为没有主键,所以无法跟踪类型的实例.只能跟踪具有主键的实体类型

Unable to track an instance of type because it does not have a primary key. Only entity types with primary keys may be tracked

public class EFContext : DbContext
{
    public DbSet<ViewItem> ViewItems { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ViewItem>().HasNoKey().ToView("vTestView");
    }
}

using (EFContext efContext = new EFContext())
{
    efContext.ViewItems.Add(new ViewItem
    {
        Name = "This is test item #1"
    });

    efContext.SaveChanges();
}

推荐答案

解决方法:

更新:要保留测试时间"和运行时"之间被测属性的行为,您可以添加一个(按惯例)仅在测试期间使用的关键属性,并且可以将模型配置为在不使用该属性时忽略该属性在测试中:

UPDATE: To preserve the behavior of the Properties Under Test between Test Time and Runtime, you could add a key property that (by convention) you only use during testing, and you configure the model to ignore the property when you are not in testing:

public class ViewItem 
{
    public int TestOnlyKey { get; set; }
    public string Name { get; set; }
}
public class EFContext : DbContext
{
    public DbSet<ViewItem> ViewItems { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ViewItem>(entity =>
        {
            if (!Database.IsInMemory())
            {
                entity.HasNoKey();
                entity.Ignore(e => e.TestOnlyKey);
                entity.ToView("vTestView");
            }
            else
            {
                entity.HasKey(e => e.TestOnlyKey);
            }
        });
    }
}

这篇关于如何在无密钥内存的情况下对EF Core 3视图进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆