Skip to content

Instantly share code, notes, and snippets.

@TAGC
Last active March 29, 2023 12:39
Show Gist options
  • Save TAGC/aba5a49c185328662816cab862c34e34 to your computer and use it in GitHub Desktop.
Save TAGC/aba5a49c185328662816cab862c34e34 to your computer and use it in GitHub Desktop.
EF Core migration generation issue
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Experiment.Lib
{
public sealed class BranchContext : DbContext
{
public DbSet<Order> Orders { get; set; }
// Uncommenting this causes a different migration to be generated.
//public DbSet<Vehicle> Vehicles { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("foo");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(MapToViewOwningVehicle); // Fails with NullReferenceException
//modelBuilder.Entity<Order>(MapToViewWithKeys); // Okay
//modelBuilder.Entity<Order>(MapToViewNotOwningVehicle); // Okay
//modelBuilder.Entity<Order>(MapToTableOwningVehicle); // Okay
}
private static void MapToViewOwningVehicle(EntityTypeBuilder<Order> builder)
{
builder.ToView("vw_OrderStatus_Orders");
builder.OwnsOne(o => o.Vehicle);
}
private static void MapToViewWithKeys(EntityTypeBuilder<Order> builder)
{
builder.ToView("vw_OrderStatus_Orders");
builder.HasKey(o => o.OrderId);
builder.OwnsOne(o => o.Vehicle, vb => vb.HasKey(v => v.Id));
}
private static void MapToViewNotOwningVehicle(EntityTypeBuilder<Order> builder)
{
builder.ToView("vw_OrderStatus_Orders");
}
private static void MapToTableOwningVehicle(EntityTypeBuilder<Order> builder)
{
builder.ToTable("vw_OrderStatus_Orders");
builder.OwnsOne(o => o.Vehicle);
}
}
}
namespace Experiment.Lib
{
public class Order
{
public int OrderId { get; set; }
public Vehicle Vehicle { get; set; }
}
}
namespace Experiment.Lib
{
public class Vehicle
{
public int Id { get; set; }
}
}
@DevWink
Copy link

DevWink commented Mar 29, 2023

The comment where it says it will migrate elsewhere can be changed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment