Last active
March 29, 2023 12:39
-
-
Save TAGC/aba5a49c185328662816cab862c34e34 to your computer and use it in GitHub Desktop.
EF Core migration generation issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Experiment.Lib | |
{ | |
public class Order | |
{ | |
public int OrderId { get; set; } | |
public Vehicle Vehicle { get; set; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Experiment.Lib | |
{ | |
public class Vehicle | |
{ | |
public int Id { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The comment where it says it will migrate elsewhere can be changed.