How to unit test EF core 3 view with no key in-memory?

ef-core-3.0 entity-framework-core

Question

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();
}
1
5
1/7/2020 9:22:12 AM

Popular Answer

Workaround: IsInMemory()

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ViewItem>(entity =>
    {
        if (!Database.IsInMemory())
        {
            entity.HasNoKey();
            entity.ToView("vTestView");
        }
        else
        {
            entity.HasKey(e => e.Name);
        }
    });
}

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);
            }
        });
    }
}
0
4/18/2020 1:47:14 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow