I have an Entity Framework Core code-first database and a .Net 5 application. I have seeded some initial values into a table using the .HasData method.
Here is the gist of my RailcarEvent entity class:
public class RailcarEvent
{
public Guid RailcarEventId { get; set; }
public string Identifier { get; set; }
}
I created a helper class that contains the IDs for some of these RailcarEvents. The main advantage here is that since these Guids are declared in a static class, I can use RailcarEventIdentifiers kind of like an enum.
public static class RailcarEventIdentifiers
{
public static readonly Guid ArriveDest = new Guid("49DB8ECD-1D26-46A1-BD39-AF358EDEB17D");
public static readonly Guid ArriveInTransit = new Guid("8F3D8BE4-E745-406D-B361-1A81B9A5C410");
public static readonly List<RailcarEvent> All = new()
{
new RailcarEvent
{
RailcarEventId = ArriveDest,
Identifier = "Arrive Dest"
},
new RailcarEvent
{
RailcarEventId = ArriveInTransit,
Identifier = "Arrive In-Transit"
}
};
}
For example, this allows me to compare property myRailcar.RailcarEventId to RailcarEventIdentifiers.ArriveDest in my code.
I have seeded the RailcarEvent table in my DbContext like so:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<RailcarEvent>().HasData(RailcarEventIdentifiers.All);;
}
My application is also able to dynamically add entries to the RailcarEvent entity if a new event is detected. For this entity, it happens infrequently enough that I am okay with checking the table once in a while to see what the new events are, then manually add them to the code with the Guid from the table.
I want the ability to reference these new application-created RailcarEvents in the same way as the others in my code, but when I add the application-created RailcarEvents to my RailcarEventIdentifiers.All list and attempt a migration, I get conflicting key errors saying that the data already exists in the database (and it does). I don't care that it already exists and would just like to ignore this error and continue.
Is there a way to create a migration that will not cause these conflicting key errors?
Is there a better way to track these static IDs? I'd be open to hearing that as well.