Ignore Entities that are marked as Owned
Closed this issue · 5 comments
I am currently trying to use the NSubstitute implementation for some Component testing of API Services.
However, as I have some Entities that are "Owned" when I create the Mocked DbContext I am getting errors like:
Cannot create a DbSet for 'EntityType' because it is configured as an owned entity type and must be accessed through its owning entity type.
From looking at the code, it appears that a Set Substitute is being created for all the Entity types.
Should this instead only try to mock the relevant DbSet properties that are defined in the DbContext type?
For the NSub version, yes all sets are set up automatically.
Moq is a little different in that I set them up on demand, which is performance decision. NSub doesn't have the same issue, hence the difference in functionality.
Is the issue because a set is not marked as virtual? Can you provide more information on the use case.
I've modified the NSub implementation to set up db sets on demand so I would expect this issue to be resolved. This change has been included in the latest releases, please retry the failure case and let me know if the issue still persists.
Sorry, will grab the latest and test it tomorrow.
I used the following as my test case for this which reproduced your issue with version 3.0.1 and showed it as resolved in 3.0.2.
void Main()
{
var fixture = new Fixture();
var orders = fixture.CreateMany<Order>().ToList();
var mockedDbContext = Create.MockedDbContextFor<OwnedEntityContext>();
mockedDbContext.Orders.AddRange(orders);
mockedDbContext.SaveChanges();
mockedDbContext.Orders.ToList().Should().BeEquivalentTo(orders);
}
public class Order
{
public int Id { get; set; }
public StreetAddress ShippingAddress { get; set; }
}
public class StreetAddress
{
public string Street { get; set; }
public string City { get; set; }
}
public class OwnedEntityContext : DbContext
{
public virtual DbSet<Order> Orders { get; set; }
public OwnedEntityContext(DbContextOptions<OwnedEntityContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>().OwnsOne(p => p.ShippingAddress);
}
}
Hi, Sorry for late reply. This does seem to fix my issue. Many Thanks.