Skip to content

Instantly share code, notes, and snippets.

@alewkowicz
Created July 14, 2017 16:33
Show Gist options
  • Save alewkowicz/a75add41d1d2165f8a100539a4700d98 to your computer and use it in GitHub Desktop.
Save alewkowicz/a75add41d1d2165f8a100539a4700d98 to your computer and use it in GitHub Desktop.
Demonstrating AutoMapper.Collection issue
namespace TruckTech.Data.Config
{
internal class EventConfig : EntityTypeConfiguration<Event>
{
public EventConfig()
{
// Primary key is part of identifying relationship
HasKey(e => new { e.LogId, e.Id });
Property(e => e.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(e => e.LogId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
HasRequired(e => e.Log)
.WithMany(l => l.Events)
.HasForeignKey(e => e.LogId)
.WillCascadeOnDelete();
}
}
}
[TestMethod]
public void SimplifiedExampleOfUnwantedBehavior()
{
var desiredDate = DateTime.Parse("7/12/2017");
// This is just the API wrapper. It doesn't use AutoMapper so I'm not including that code.
var fetcher = CreateRawFetcher().ConfigureDateRange(desiredDate, desiredDate);
var rawLogs = fetcher.GetUnmappedList();
Assert.IsTrue(rawLogs.Any());
// Get a raw Log entry from the list, one that has events, since we're testing how the Event objects are handled.
var rawLogWithEvents = rawLogs.First(log => log.Events != null && log.Events.Any());
// Verify this log entry is already in the database.
var context = new TruckTechContext();
var matchingLog = context.Logs.Find(rawLogWithEvents.Id);
Assert.IsNotNull(matchingLog);
Assert.IsTrue(matchingLog.Events.Any());
// OK, we don't need the matchingLog object anymore.
// get ready to map
var mapper = mappingConfig.CreateMapper();
var persistence = context.Logs.Persist<Db.Log>(mapper);
persistence.InsertOrUpdate(rawLogWithEvents);
// Check what happened in the DbContext:
var eventEntries = context.ChangeTracker.Entries<Db.Event>();
var addedEntries = eventEntries.Where(entry => entry.State == EntityState.Added);
var deletedEntries = eventEntries.Where(entry => entry.State == EntityState.Deleted);
var modifiedEntries = eventEntries.Where(entry => entry.State == EntityState.Modified);
// Based on the behavior I saw, I would expect one Event deleted and one Event added for every
// Event object belonging to the matching Log in the database.
Assert.AreEqual(matchingLog.Events.Count, addedEntries.Count() );
Assert.AreEqual(matchingLog.Events.Count, deletedEntries.Count() );
// I would expect 0 modified entries.
Assert.AreEqual(0, modifiedEntries.Count());
}
public static MapperConfiguration CreateConfiguration()
{
return new MapperConfiguration(cfg =>
{
cfg.AddCollectionMappers();
cfg.SetGeneratePropertyMaps<GenerateEntityFrameworkPrimaryKeyPropertyMaps<TruckTechContext>>();
// Profile has all the mapping specifics.
cfg.AddProfile(new TruckTechMappingProfile());
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment